UNPIVOT列转行(回答csdn的https://ask.csdn.net/questions/713436提问,比较有意思的问题)

版权声明:所有文章禁止转载但是均可在生产中使用提高效率 https://blog.csdn.net/viviliving/article/details/84306373

问题来源:https://ask.csdn.net/questions/713436

参考答案:

测试表:

create table table1(id number,p1 number,p2 number,p3 number);

SQL> insert into table1 select 1,1,2,3 from dual;
1 row inserted

SQL> insert into table1 select 2,5,4,3 from dual;
1 row inserted

SQL> insert into table1 select 3,7,9,8 from dual;
1 row inserted
 

要求:

找出table1中每行最大的二列的列名

语法:

create view UNPIVOTview as 
with UNPIVOTtable as (
SELECT id, DECODE(Puarter, 'P1', 'P1', 'P2', 'P2', 'P3', 'P3') AS Puarter, Puantity_sold
FROM  Table1
   UNPIVOT INCLUDE NULLS
       (Puantity_sold
        FOR Puarter IN (p1, p2, p3))
ORDER BY id) 
select * from (
select id,Puantity_sold,Puarter,mod(rownum,3) rn  from (
select id,Puantity_sold,Puarter from UNPIVOTtable order  by id,Puantity_sold desc)
)
where rn between 1 and 2
;
 

SELECT id, listagg(PUARTER, ',') within group(order by id,PUANTITY_SOLD desc) pid 
 FROM UNPIVOTview
 group by id;

效果:

SQL> select * from table1;
        ID         P1         P2         P3
---------- ---------- ---------- ----------
         1          1          2          3
         2          5          4          3
         3          7          9          8

SQL> select * from UNPIVOTview;
        ID PUANTITY_SOLD PUARTER         RN
---------- ------------- ------- ----------
         1             3 P3               1
         1             2 P2               2
         2             5 P1               1
         2             4 P2               2
         3             9 P2               1
         3             8 P3               2
6 rows selected

    SELECT id, listagg(PUARTER, ',') within group(order by id,PUANTITY_SOLD desc) pid 
 FROM UNPIVOTview
 group by id;

   ID PID
---------- --------------------------------------------------------------------------------
         1 P3,P2
         2 P1,P2
         3 P2,P3

猜你喜欢

转载自blog.csdn.net/viviliving/article/details/84306373