转换行中的列名

问题描述 投票:1回答:4

我正在尝试将row name转换为row的值。结果应该是具有column name和result的两列(键,值)。有可能吗?

Select Column1, Column2, Column3 From Table A

结果是:

Column1 | Column2 | Column3
John    | Monica  | Antony

我想转换为:

KEY     | VALUE
Column1 | John
Column2 | Monica
Column3 | Antony

我该怎么做?

sql sql-server tsql unpivot
4个回答
0
投票

您可以使用union all取消透视:

select 'Column1' key, column1 value from tableA
union all select 'Column2' key, column2 from tableA
union all select 'Column3' key, column3 from tableA

某些RDBMS具有内置功能,无法取消透视; union all是跨RDBMS解决方案。



0
投票

您未指定DBMS,因此以下是使用VALUES子句的标准ANSI SQL:

select b.*
from table_a a
  cross join lateral (
     values 
       ('column1', a.column1),
       ('column2', a.column2),
       ('column3', a.column3)
  ) as b(key, value);

在线示例:https://rextester.com/QGGVR16169


0
投票

如果unpivot支持您的dbms,则可以这样做

select u.key,u.VALUE
from table s
unpivot
(
  VALUE
  for Key in (Column1, Column2, Column3)
) u
© www.soinside.com 2019 - 2024. All rights reserved.