【问题标题】:Transpose rows to columns based on ID column根据 ID 列将行转置为列
【发布时间】:2013-11-01 03:24:36
【问题描述】:

我目前正在运行 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 运算符(2005+)。玩得开心! (任何不需要动态 SQL 或某些过程代码的解决方案都将被限制为必须在查询中指定的输出列的固定集。)

标签: sql sql-server sql-server-2008


【解决方案1】:

您可以为此使用 SQL Server 数据透视子句:

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

【讨论】:

  • 嗨罗曼,感谢您的建议。我目前收到“操作数数据类型 ntext 对 max 运算符无效”。只是为了澄清字段名称和选择列是文本而不是 ID。
  • 绝对传奇!将其作为 nvarchar 在 sub 中对其进行排序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2015-04-26
  • 2018-02-25
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多