UNPIVOT on multiple columns to return multiple columns

孤街醉人 提交于 2019-12-13 03:44:44

问题


Below is the requirement to be acheived in PL/SQL-

The table format is

CREATE TABLE NETWORK_TABLE ( ORIG_CODE NUMBER, ORIG_SV NUMBER, DEST_CODE NUMBER, DEST_SV NUMBER )

Sample Data -

INSERT INTO network_table VALUES ( 14, 1, 15, 1);

INSERT INTO network_table VALUES ( 18, 4, 11, 1);

INSERT INTO network_table VALUES ( 15, 1, 22, 3);

INSERT INTO network_table VALUES ( 23, 2, 21, 1);

INSERT INTO network_table VALUES ( 14, 3, 11, 1);

INSERT INTO network_table VALUES ( 12, 2, 22, 2);

Table data looks like -

Orig_r  orig_sv  dest_r dest_sv
  14     1       15     1 
  12     2       22     2 
  18     4       11     1 
  15     1       22     3 
  14     3       11     1 

Now, I want to get the output as below -

ROOT SV
14   1 
15   1  
12   2
22   2
18   4
11   1
15   1
22   3
14   3
1    1

How can I acheive this? Appreciate your input


回答1:


like this:

SQL> select * from network_table;

 ORIG_CODE    ORIG_SV  DEST_CODE    DEST_SV
---------- ---------- ---------- ----------
        14          1         15          1
        12          2         22          2
        18          4         11          1
        15          1         22          3
        14          3         11          1

SQL> select case name when 'ORIG_SV' then orig_code else dest_code end code, val 
  2  from network_table 
  3  unpivot (val for name in (orig_sv, dest_sv));

      CODE        VAL
---------- ----------
        14          1
        15          1
        12          2
        22          2
        18          4
        11          1
        15          1
        22          3
        14          3
        11          1

or 10g and below:

SQL> select case  r when 1 then orig_code else dest_code end code,
  2         case r when 1 then orig_sv else dest_sv end val
  3    from network_table, (select rownum r from dual connect by level <= 2)
  4  /

      CODE        VAL
---------- ----------
        14          1
        12          2
        18          4
        15          1
        14          3
        15          1
        22          2
        11          1
        22          3
        11          1



回答2:


You can use a UNION ALL to transform the data from columns into rows.:

select ORIG_CODE Root, ORIG_SV SV
from network_table
union all
select DEST_CODE, DEST_SV  
from network_table
order by root

See SQL Fiddle with Demo

The UNION ALL will leave any duplicate values. If you want to remove the duplicates, then you can use UNION



来源:https://stackoverflow.com/questions/14365848/unpivot-on-multiple-columns-to-return-multiple-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!