根据 ID 列将行转置为列 [英] Transpose rows to columns based on ID column
本文介绍了根据 ID 列将行转置为列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在运行 SQL Server 2008 并尝试获取以下子查询数据:
I'm currently running SQL Server 2008 and trying to get the following subquery data:
ID | Field Name | Field Selection
1 | Rating 1 | Good
1 | Rating 2 | Good
1 | Rating 3 | Bad
2 | Rating 1 | OK
根据 ID 列分组为一行:
Grouped into a single row based on the ID column:
ID | Rating 1 | Rating 2 | Rating 3
1 | Good | Good | Bad
2 | OK | NULL | NULL
这可能吗?提前致谢!
干杯,硅
推荐答案
您可以为此使用 SQL Server 数据透视子句:
you can use SQL Server pivot clause for this:
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
这篇关于根据 ID 列将行转置为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文