sql – 根据ID列将行转换为列

前端之家收集整理的这篇文章主要介绍了sql – 根据ID列将行转换为列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前正在运行sql Server 2008并尝试获取以下子查询数据:
ID | Field Name | Field Selection
1  |  Rating 1  |      Good
1  |  Rating 2  |      Good
1  |  Rating 3  |      Bad
2  |  Rating 1  |      OK

根据ID列分组为一行:

ID | Rating 1 | Rating 2 | Rating 3
1  |    Good  |    Good  |   Bad
2  |     OK   |    NULL  |   NULL

这可能吗?提前致谢!

干杯,

解决方法

您可以使用sql Server pivot子句:
select
    p.*
from Table1
pivot(
    max([Field Selection])
    for [Field Name] in ([Rating 1],[Rating 2],[Rating 3])
) as p

或者你可以手动转动:

select
    ID,max(case when [Field Name] = 'Rating 1' then [Field Selection] end) as [Rating 1],max(case when [Field Name] = 'Rating 2' then [Field Selection] end) as [Rating 2],max(case when [Field Name] = 'Rating 3' then [Field Selection] end) as [Rating 3]
from Table1
group by ID

sql fiddle demo

原文链接:https://www.f2er.com/mssql/80333.html

猜你在找的MsSQL相关文章