Salah satu cara untuk melakukannya jika tagID
nilai yang diketahui di muka adalah dengan menggunakan agregasi bersyarat
SELECT TimeSeconds,
COALESCE(MAX(CASE WHEN TagID = 'A1' THEN Value END), 'n/a') A1,
COALESCE(MAX(CASE WHEN TagID = 'A2' THEN Value END), 'n/a') A2,
COALESCE(MAX(CASE WHEN TagID = 'A3' THEN Value END), 'n/a') A3,
COALESCE(MAX(CASE WHEN TagID = 'A4' THEN Value END), 'n/a') A4
FROM table1
GROUP BY TimeSeconds
atau jika Anda setuju dengan NULL
nilai alih-alih 'n/a'
SELECT TimeSeconds,
MAX(CASE WHEN TagID = 'A1' THEN Value END) A1,
MAX(CASE WHEN TagID = 'A2' THEN Value END) A2,
MAX(CASE WHEN TagID = 'A3' THEN Value END) A3,
MAX(CASE WHEN TagID = 'A4' THEN Value END) A4
FROM table1
GROUP BY TimeSeconds
atau dengan PIVOT
SELECT TimeSeconds, A1, A2, A3, A4
FROM
(
SELECT TimeSeconds, TagID, Value
FROM table1
) s
PIVOT
(
MAX(Value) FOR TagID IN (A1, A2, A3, A4)
) p
Keluaran (dengan NULL
s):
TimeSeconds A1 A2 A3 A4----------- ------- ------ ----- -----1378700244 3.75 NULL NULL NULL1378700245 30.00 NULL NULL 0Jika Anda harus mencari
TagID
nilai keluar secara dinamis kemudian gunakan SQL dinamisDECLARE @cols NVARCHAR(MAX), @sql NVARCHAR(MAX) SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(TagID) FROM Table1 ORDER BY 1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'') SET @sql = 'SELECT TimeSeconds, ' + @cols + ' FROM ( SELECT TimeSeconds, TagID, Value FROM table1 ) s PIVOT ( MAX(Value) FOR TagID IN (' + @cols + ') ) p' EXECUTE(@sql)