如果系列固定为 a,b,c 你可以这样做:
CREATE TABLE #t (Id INT, Year INT,
Series VARCHAR(5), Value DECIMAL(10,1))
INSERT #t
VALUES
(1, 1990, 'a', 1.5),
(1, 1990, 'b', 1.6),
(1, 1990, 'c', 1.7),
(1, 1991, 'a', 1.8),
(1, 1991, 'b', 1.9),
(1, 1991, 'c', 2.5)
SELECT pvt.Year,
pvt.a,
pvt.b,
pvt.c
FROM #t
PIVOT (
MIN(Value) FOR Series IN ([a], [b], [c])
) pvt
如果还有其他值,您可以使用动态枢轴:
DECLARE @series VARCHAR(100) =
STUFF(( SELECT DISTINCT ',[' + Series + ']'
FROM #t
FOR XML PATH(''))
,1, 1, '')
DECLARE @query VARCHAR(2000) = '
SELECT pvt.Year, ' + @series +'
FROM #t
PIVOT (
MIN(Value) FOR Series IN (' + @series + ')
) pvt
';
EXEC(@query)
在具有固定系列的场景中,CROSS JOIN 也有可能:
SELECT a.Year,
MAX(CASE WHEN a.Series = 'a' THEN a.Value END) a,
MAX(CASE WHEN a.Series = 'b' THEN a.Value END) b,
MAX(CASE WHEN a.Series = 'c' THEN a.Value END) c
FROM #t a
CROSS JOIN #t b
GROUP BY a.Id, a.Year
ORDER BY a.Year