表: SampleTbl
Values Name
---------------------
23 id
33 b_id
2014-12-10 Date
55 t_id
NULL p_id
NULL comments
24 id
34 b_id
2014-12-11 Date
56 t_id
NULL p_id
NULL comments
预期结果:
id b_id Date t_id p_id comments
------------------------------------------------------
23 33 2014-12-10 55 NULL NULL
24 34 2014-12-10 56 NULL NULL
我尝试过使用PIVOT
,
SELECT * FROM
SampleTbl
Pivot (MIN ([Values]) FOR Name IN ([id],[b_id],[Date],[t_id],[p_id],[comments])) piv
我得到的结果:
id b_id Date t_id p_id comments
---------------------------------------------------
23 33 2014-12-10 55 NULL NULL
但我没有得到预期的结果。帮助我得到结果。
答案 0 :(得分:2)
试试这个。使用window function
获取结果。
SELECT [id],[b_id],[Date],
[t_id],[p_id],[comments]
FROM (SELECT Row_number()OVER(partition BY name ORDER BY [values]) rn,*
FROM SampleTbl) A
PIVOT (Min ([Values])
FOR Name IN ([id],[b_id],[Date],
[t_id],[p_id],[comments])) piv