这对于 UNPIVOT 是不可能的,您需要使用 PIVOT。有关该主题的 Microsoft 文档"Using PIVOT and UNPIVOT"
但这里有一个使用 cmets 测试数据的示例:
DECLARE @Custom TABLE
(
[ID] TINYINT IDENTITY
, [value] NVARCHAR(20)
);
INSERT INTO @Custom
VALUES ( 'red' )
, ( 'green' )
, ( 'blue' );
SELECT *
FROM @Custom
PIVOT (
MAX([value]) --column being aggregated, the column values you want horizontal
FOR [ID] IN ( [1], [2], [3] ) --The column that contains the value that will become the column headers.
) AS [pvt];
给予使用的结果
1 2 3
-------------------- -------------------- --------------------
red green blue
由于您希望在列标题中使用“COLOR”的措辞,我们将在子查询中将其与 ID 列连接并调整枢轴
SELECT *
FROM (
--Since you want 'COLOR' as part of the column name we do a sub-query and concat that verbiage with the ID
SELECT CONCAT('COLOR', [ID]) AS [ColumnColor]
, [value]
FROM @Custom
) AS [Cst]
PIVOT (
MAX([value]) --Same as before, column being aggregated, the column values you want horizontal
FOR [ColumnColor] IN ( [COLOR1], [COLOR2], [COLOR3] ) --This changes now to reflect the concatenated column and the new column header values
) AS [pvt];
给我们结果
COLOR1 COLOR2 COLOR3
-------------------- -------------------- --------------------
red green blue