sql server - 如何将行设置为列?

时间:2018-01-19 11:50:06

标签: sql-server sql-server-2012

希望有人可以帮助我。我有一个看起来像下面的表

ID  | Column | New Value | ModifiedDate

223 | Num    | 98        | 03/01/2018
223 | Country| IRE       | 03/01/2018
223 | User   | Bob       | 03/01/2018
222 | User   | Lily      | 01/01/2018
222 | Num    | 72        | 01/01/2018
222 | Country| UK        | 01/01/2018
222 | User   | Wendy     | 02/01/2018
222 | Num    | 22        | 02/01/2018
222 | Country| UK        | 02/01/2018

我想要一个基于ID和修改日期以某种方式将所有这些合并到行中的查询。所以对于上表,我想要以下输出

ID  | Num | Country | User | Modified Date
222 |  72 |   UK    | Lily | 01/01/2018
222 |  22 |   UK    |Wendy | 02/01/2018
223 |  98 |  IRE    | Bob  | 03/01/2018

有人可以帮忙吗?我在这里寻找类似的问题,但是当我在桌子上使用它时找不到任何实际工作的东西?

此外,ID的数量可以改变,因此它必须是动态的吗?

非常感谢任何帮助!!

2 个答案:

答案 0 :(得分:0)

简单如下:

SELECT * 
FROM TableName
   PIVOT ( MAX(NewValue)
           FOR [Column]
           IN ([Num] , [Country] , [User])
         )p

答案 1 :(得分:0)

Old-School pivoting也可以

select 
ID, 
max(case when [Column] = 'Num' then [New Value] end) as Num,
max(case when [Column] = 'Country' then [New Value] end) as Country,
max(case when [Column] = 'User' then [New Value] end) as [User],
ModifiedDate
from YourTable 
group by ID, ModifiedDate
order by ID, ModifiedDate;