2016-06-30 22 views
0

Ich habe Tabelle A als meine Eingabe in Oracle SQL. Tabelle A:Eine Spalte horizontal in mehrere Spalten basierend auf einem gemeinsamen Wert in einer anderen Spalte teilen

+-----------+---------+------+-----+ 
| Col1 | Col2 | Col3 | Col4| 
+-----------+---------+------+-----+ 
|  a | g | 1 | ABC | 
|  b | h | 2 | ABC | 
|  c | i | 1 | DEF | 
|  d | j | 2 | DEF | 
|  e | k | 1 | GHI | 
|  f | l | 2 | GHI | 
+-----------+---------+------+-----+ 

Ich möchte 2 horizontal jeder der Spalte 1 und Spalte aufzuspalten, basierend auf dem Wert von col4. Col3 ist entweder 1 oder 2 wie gezeigt. Ausgabetabelle:

+-----------+---------+------+-----+----+ 
| Col5 | Col6 | Col7 | Col8|Col9| 
+-----------+---------+------+-----+----+ 
|  a | g | b | h | ABC| 
|  c | i | d | j | DEF| 
|  e | k | f | l | GHI| 
+-----------+---------+------+-----+----+ 

Antwort

0

Ich glaube, Sie nur bedingte Aggregation wollen:

select max(case when col3 = 1 then col1 end) as col5, 
     max(case when col3 = 1 then col2 end) as col6, 
     max(case when col3 = 2 then col1 end) as col7, 
     max(case when col3 = 2 then col2 end) as col8, 
     col4 as col9 
from tablea a 
group by col4; 
1

Oracle-Setup:

CREATE TABLE table_name (Col1, Col2, Col3, Col4) 
    SELECT 'a', 'g', 1, 'ABC' FROM DUAL UNION ALL 
    SELECT 'b', 'h', 2, 'ABC' FROM DUAL UNION ALL 
    SELECT 'c', 'i', 1, 'DEF' FROM DUAL UNION ALL 
    SELECT 'd', 'j', 2, 'DEF' FROM DUAL UNION ALL 
    SELECT 'e', 'k', 1, 'GHI' FROM DUAL UNION ALL 
    SELECT 'f', 'l', 2, 'GHI' FROM DUAL; 

Abfrage:

SELECT N1_C1 AS Col5, 
     N1_C2 AS Col6, 
     N2_C1 AS Col7, 
     N2_C2 AS Col8, 
     Col4 AS Col9 
FROM table_name 
PIVOT (MAX(Col1) AS C1, MAX(Col2) AS C2 
     FOR Col3 IN (1 AS N1, 2 AS N2)); 

Ausgang:

COL5 COL6 COL7 COL8 COL9 
---- ---- ---- ---- ---- 
a g b h ABC 
c i d j DEF 
e k f l GHI 
1

Dies ist eine gerade Anwendung einer Selbstverknüpfung:

with 
    test_data (col1, col2, col3, col4) as ( 
     select 'a', 'g', 1, 'ABC' from dual union all 
     select 'b', 'h', 2, 'ABC' from dual union all 
     select 'c', 'i', 1, 'DEF' from dual union all 
     select 'd', 'j', 2, 'DEF' from dual union all 
     select 'e', 'k', 1, 'GHI' from dual union all 
     select 'f', 'l', 2, 'GHI' from dual 
    ) 
select td1.col1 as col5, td1.col2 as col6, td2.col1 as col7, 
     td2.col2 as col8, td1.col4 as col9 
from test_data td1 inner join test_data td2 on td1.col4 = td2.col4 
where td1.col3 = 1 and td2.col3 = 2 
; 

COL5 COL6 COL7 COL8 COL9 
---- ---- ---- ---- ---- 
a g b h ABC 
c i d j DEF 
e k f l GHI 
Verwandte Themen