【问题标题】:Pivot or Unpivot a small table旋转或取消旋转小桌子
【发布时间】:2020-03-12 00:29:01
【问题描述】:

我很难理解枢轴/取消枢轴 - 我在网上找到的所有示例都比我需要的复杂。

想象一个这样的表格:

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

表格显示如下

ID    VALUE
1     red
2     green
3     blue

我希望表格显示为

COLOR1    COLOR2    COLOR3
red       green     blue

这可以通过 UNPIVOT 实现吗?

谢谢!

【问题讨论】:

  • UNPIVOT 无法做到这一点。

标签: sql tsql pivot unpivot


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    这对于 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-31
      • 2012-06-19
      • 2014-07-26
      • 2016-01-08
      相关资源
      最近更新 更多