我正在尝试将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
我该怎么做?
您可以使用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解决方案。
您未指定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);
如果unpivot支持您的dbms,则可以这样做
select u.key,u.VALUE
from table s
unpivot
(
VALUE
for Key in (Column1, Column2, Column3)
) u