Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 基于ID列将行转换为列_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql 基于ID列将行转换为列

Sql 基于ID列将行转换为列,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我当前正在运行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 | Goo

我当前正在运行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
这可能吗?提前谢谢

干杯,
Si

您可以使用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 Server(耶!),请查看操作员(2005+)。玩得高兴(任何不需要动态SQL或某些过程代码的解决方案都将被限制为必须在查询中指定的一组固定输出列。)Hi Roman,感谢您的建议。我当前收到“操作数数据类型ntext对于max运算符无效”。只是为了澄清字段名和选择列是文本,而不是ID的绝对图例!在子目录中将其转换为nvarchar。