如何在 SQL Server 中转置查询结果(行到列)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42287383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 05:08:04  来源:igfitidea点击:

How to transpose a query result in SQL Server (rows to columns)

sqlsql-server-2008

提问by JPacheco

my query gives me a result as follows:

我的查询给了我如下结果:

initial query

初始查询

so, i want to transform that result into this:

所以,我想把结果变成这样:

query transformed

查询转换

Note the crossing fields with NULL values.

请注意具有 NULL 值的交叉字段。

采纳答案by Paul

PIVOT is the way to accomplish this and it can be confusing (at least it was to me) at first.

PIVOT 是实现这一目标的方法,一开始可能会令人困惑(至少对我来说是这样)。

https://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query

https://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query

回答by JPacheco

I have found a nice solution to my problem thanks to @[P Doe], for guiding me to the solution.

感谢@[P Doe],我找到了一个很好的解决方案,指导我找到解决方案。

The link is:

链接是:

Dynamic PIVOT in Sql Server

Sql Server 中的动态 PIVOT

回答by Javlon Ismatov

 select id,SN,
 case Part when 'P1' then '1' else null end 'P1',
 case Part when 'P2' then '1' else null end 'P2',
 case Part when 'P3' then '1' else null end 'P3',
 case Part when 'P4' then '1' else null end 'P4',
 case Part when 'P5' then '1' else null end 'P5'
  from table1