【问题标题】:Unpivot (or alternative) all columns into rows将所有列取消透视(或替代)成行
【发布时间】:2020-01-01 19:03:50
【问题描述】:

我有以下数据:

create table test(c1 number,
                  c2 number,
                  c3 number,
                  c4 number,
                  c5 number);

insert into test (c1,c2,c3,c4,c5) values(2000,1844054,50.03,922030,25.01);
insert into test (c1,c2,c3,c4,c5) values(2001,1850861,49.86,937391,25.25);
insert into test (c1,c2,c3,c4,c5) values(2002,1841519,50.32,907995,24.81);
insert into test (c1,c2,c3,c4,c5) values(2003,1804163,49.84,902838,24.94);

我需要从以下位置翻译数据:

c1   | c2      | c3    | c4     | c5
2000 | 1844054 | 50.03 | 922030 | 25.01
2001 | 1850861 | 49.86 | 937391 | 25.25
2002 | 1841519 | 50.32 | 907995 | 24.81
2003 | 1804163 | 49.84 | 902838 | 24.94

到:

c1 | 2000    | 2001    | 2002    | 2003
c2 | 1844054 | 1850861 | 1841519 | 1804163
c3 | 50.03   | 49.86   | 50.32   | 49.84
c4 | 922030  | 937391  | 907995  | 902838
c5 | 25.01   | 25.25   | 24.81   | 24.94

我没有成功进行常规 PIVOT,所以我向您寻求帮助,谢谢。

【问题讨论】:

    标签: sql oracle unpivot


    【解决方案1】:

    您正在转置,而不仅仅是旋转。你需要UNPIVOT,然后PIVOT

    select * from test
    unpivot(c for col in(c2,c3,c4,c5))
    pivot(max(c) for c1 in(2000,2001,2002,2003))
    order by col;
    
    CO       2000       2001       2002       2003
    -- ---------- ---------- ---------- ----------
    C2    1844054    1850861    1841519    1804163
    C3      50.03      49.86      50.32      49.84
    C4     922030     937391     907995     902838
    C5      25.01      25.25      24.81      24.94
    

    【讨论】:

      【解决方案2】:

      这是一种痛苦。您可以取消透视并重新聚合。这是一种方法:

      select which,
             max(case when year = 2000 then c end) as val_2000,
             max(case when year = 2001 then c end) as val_2001,
             max(case when year = 2002 then c end) as val_2002,
             max(case when year = 2003 then c end) as val_2003
      from ((select c1 as year, 'c2' as which, c2 as c from test) union all
            (select c1 as year, 'c3' as which, c3 as c from test) union all
            (select c1 as year, 'c4' as which, c4 as c from test) union all
            (select c1 as year, 'c5' as which, c5 as c from test) 
           ) x
      group by which
      order by which;
      

      Here 是一个 dbfiddle。

      【讨论】:

        【解决方案3】:
         SELECT * FROM test
         unPIVOT(
            quantity -- unpivot_clause
            FOR product_code --  unpivot_for_clause
            IN ( c2,c3,c4,c5)) 
        
        pivot(max(quantity) for 
        c1 in(2000,2001,2002,2003))
        order by product_code;
        

        【讨论】:

        • 这与 Stew Ashton 已经发布的答案有何不同?
        猜你喜欢
        • 2019-05-20
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 2017-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多