You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求编写SQL实现单行多列转多行两列,Unpivot方法无效

单行数据转列名-值对的SQL查询方案

需求说明

已知Table1仅包含单行数据,原表结构及数据如下:

ColumnAColumnBColumnCColumnD
Cell 1Cell 2Cell 3Cell 4

需要将其转换为如下格式的结果:

NewColumn1NewColumn2
ColumnACell 1
ColumnBCell 2
ColumnCCell 3
ColumnDCell 4

可行解决方案

方法1:使用VALUES子句(推荐,简洁高效)

适用于SQL Server、MySQL 8.0+、PostgreSQL等现代数据库:

SQL Server版本
SELECT NewColumn1, NewColumn2
FROM Table1
CROSS APPLY (
    VALUES
        ('ColumnA', ColumnA),
        ('ColumnB', ColumnB),
        ('ColumnC', ColumnC),
        ('ColumnD', ColumnD)
) AS UnpivotedData(NewColumn1, NewColumn2);
MySQL/PostgreSQL版本
SELECT NewColumn1, NewColumn2
FROM Table1
CROSS JOIN (
    VALUES
        ('ColumnA', Table1.ColumnA),
        ('ColumnB', Table1.ColumnB),
        ('ColumnC', Table1.ColumnC),
        ('ColumnD', Table1.ColumnD)
) AS UnpivotedData(NewColumn1, NewColumn2);

方法2:使用UNION ALL(兼容性最强)

几乎所有关系型数据库都支持此写法:

SELECT 'ColumnA' AS NewColumn1, ColumnA AS NewColumn2 FROM Table1
UNION ALL
SELECT 'ColumnB' AS NewColumn1, ColumnB AS NewColumn2 FROM Table1
UNION ALL
SELECT 'ColumnC' AS NewColumn1, ColumnC AS NewColumn2 FROM Table1
UNION ALL
SELECT 'ColumnD' AS NewColumn1, ColumnD AS NewColumn2 FROM Table1;

UNPIVOT失效的原因及正确写法

如果之前使用UNPIVOT未生效,大概率是以下原因:

  • UNPIVOT仅在SQL Server、Oracle等部分数据库中支持,MySQL、PostgreSQL原生不支持该语法;
  • SQL Server下正确的UNPIVOT写法:
SELECT NewColumn1, NewColumn2
FROM Table1
UNPIVOT (
    NewColumn2 FOR NewColumn1 IN (ColumnA, ColumnB, ColumnC, ColumnD)
) AS UnpivotedData;

内容的提问来源于stack exchange,提问作者Deter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 22:50:41