此查询的结果:
+--------------------------------------+-----------+--------+
| id | name | data |
+--------------------------------------+-----------+--------+
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | LMP1(FA5) | NULL |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Limits | NULL |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Low | 1 |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | High | 3 |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Units | second |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Comp | GELE |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Data | 1.8 |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Status | Passed |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | LMP2(FA6) | NULL |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Limits | NULL |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Low | 1 |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | High | 3 |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Units | second |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Comp | GELE |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Data | 1.8 |
| 4EAB4160-75FF-11E8-8719-2C56DC925591 | Status | Passed |
+--------------------------------------+-----------+--------+
我想得到这个:
我已经尝试过了,但是不是绝对的答案:
SELECT *
FROM
(
SELECT id, name, data as f FROM temp_id)t
PIVOT(MIN(f)
FOR name
IN ([LMP1 (FA5)],[Limits],[Low],[High],[Units],[Comp],[data],[Status])
)p
最好也有动态列的名称...
我感谢大家的帮助。
我已经尝试过这种动态枢纽,但它不起作用:
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT ',' + QUOTENAME(c.name)
FROM temp_id c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT id,' + @cols + ' from
(
select id
, name
, data
from temp_id
) x
pivot
(
count(name)
for name in (' + @cols + ')
) p