旋转或反旋转一个小 table

Pivot or Unpivot a small table

我很难理解 pivot/unpivot - 我认为我在网上找到的所有示例都比我需要的更复杂。

想象一个 table 这样的:

CREATE TABLE Custom (ID tinyint identity, value nvarchar(20))
INSERT INTO Custom VALUES ('red')
INSERT INTO Custom VALUES ('green')
INSERT INTO Custom VALUES ('blue')

table显示为

ID    VALUE
1     red
2     green
3     blue

我希望 table 显示为

COLOR1    COLOR2    COLOR3
red       green     blue

UNPIVOT 可以吗?

谢谢!

这是一种使用条件聚合生成所需结果的方法:

select 
    max(case when id = 1 then value end) color1,
    max(case when id = 2 then value end) color2,
    max(case when id = 3 then value end) color3
from custom

如果您没有从 1 开始的顺序 id,您可以使用 row_number():

来模拟它
select
    max(case when rn = 1 then value end) color1,
    max(case when rn = 2 then value end) color2,
    max(case when rn = 3 then value end) color3
from (select value, row_number() over(order by id) rn from mytable)

这对于 UNPIVOT 是不可能的,您需要使用 PIVOT。有关该主题的 Microsoft 文档 "Using PIVOT and UNPIVOT"

但这里有一个使用您的测试数据和注释的示例:

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

由于您想要在 headers 列中使用 'COLOR' 的措辞,我们将在 sub-query 中将其与 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