我有一个具有以下架构的表。希望在 SQL Server 中获得预期结果。由于值列是字符串,因此数据透视表不起作用。请建议实现这一目标的有效方法。谢谢!
表:
Dim Key(String) , Dim Value (String)
AB XY1
AB XY2
CD XY3
CD XY4
预期结果
New columns=> AB CD
Row values => XY1 XY3
XY2 XY4
最佳答案
您想要row_number()
:
select max(case when key = 'ab' then Value end) as ab,
max(case when key = 'cd' then Value end) as cd
from (select t.*,
row_number() over (partition by key order by Value) as seq
from table t
) t
group by seq;
但是,您的 pivot
版本也应该适用于 row_number()
。
编辑:
select tt.*
from (select t.*,
row_number() over (partition by [key] order by Value) as seq
from table t
) as t pivot
( max(value) for [key] in ([ab], [cd])
) tt;
关于sql - 将列值转换为列名 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54712720/