转换行中的列名

时间:2019-11-06 11:13:34

标签: sql sql-server tsql unpivot

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

Select Column1, Column2, Column3 From Table A

结果是:

Column1 | Column2 | Column3
John    | Monica  | Antony

我要转换为:

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

我该怎么做?

2 个答案:

答案 0 :(得分: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解决方案。

答案 1 :(得分:0)

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

select u.key,u.VALUE
from table s
unpivot
(
  VALUE
  for Key in (Column1, Column2, Column3)
) u
相关问题