2017-05-12 2 views
1

Meine Tabelle hat mehrere Werte pro Person, die ich versuche, in einer Zeile zu kombinieren. Hier ist die Abfrage:Oracle SQL - Kombinieren von Werten in einer Zeile

select TABLE.ID, 
     TABLE.NAME, 
     listagg(TABLE.HOLD, ',') within group (order by TABLE.HOLD) as hold_codes 
    from TABLE 
    where TABLE.ACTIVE_HOLD_IND ='Y' 
     and TABLE.HOLD in('S2', 'S3', 'CO', 'WO', 'PP') 
    group by 
TABLE.ID, 
TABLE.NAME, 
TABLE.HOLD 
order by 2 

ID |NAME |HOLD_CODES 
_____________________________ 
111 |Tom |S2 
222 |Jerry |CO 
222 |Jerry |S2 
333 |Olive |S2,S2 
444 |Popeye |CO 
444 |Popeye |PP 
444 |Popeye |S2 
555 |Homer |S2,S2 
666 |Marge |S2 

Ich versuche, jede ID in einer Zeile zu kombinieren. Im Moment nimmt die Abfrage nur die Dublettenreihen auf.

Irgendwelche Vorschläge würden geschätzt.

Antwort

2

Entfernen Sie TABLE.HOLD von Ihrem group by.

with cte as (
      select 111 as id,'Tom ' as name,'S2' as hold from dual 
union all select 222,'Jerry ','CO' from dual 
union all select 222,'Jerry ','S2' from dual 
union all select 333,'Olive ','S2' from dual 
union all select 444,'Popeye','CO' from dual 
union all select 444,'Popeye','PP' from dual 
union all select 444,'Popeye','S2' from dual 
union all select 555,'Homer ','S2' from dual 
union all select 666,'Marge ','S2' from dual 
) 
select 
    cte.ID 
    , cte.name 
    , listagg(cte.HOLD, ',') within group (order by cte.HOLD) as hold_codes 
from cte 
where cte.HOLD in ('S2', 'S3', 'CO', 'WO', 'PP') 
group by cte.ID 
, cte.name 
order by 2 

rextester Demo: http://rextester.com/FPFI26814

kehrt:

+-----+--------+------------+ 
| ID | NAME | HOLD_CODES | 
+-----+--------+------------+ 
| 555 | Homer | S2   | 
| 222 | Jerry | CO,S2  | 
| 666 | Marge | S2   | 
| 333 | Olive | S2   | 
| 444 | Popeye | CO,PP,S2 | 
| 111 | Tom | S2   | 
+-----+--------+------------+ 
1

Ist id einmalig pro Zeile oder pro Person? Hier finden Sie sicher unabhängig:

select t.NAME, 
     listagg(t.HOLD, ',') within group (order by t.HOLD) as hold_codes 
from TABLE t 
where t.ACTIVE_HOLD_IND = 'Y' and 
     t.HOLD in('S2', 'S3', 'CO', 'WO', 'PP') 
group by t.NAME 
order by NAME; 

Offensichtlich braucht HOLD die von GROUP BY entfernt werden, aber ID müssen möglicherweise auch auch entfernt werden.

Verwandte Themen