2017-05-12 3 views
1

私のテーブルには1人あたり複数の値がありますが、これは1つの行にまとめようとしています。クエリは次のとおりです。Oracle SQL - 値を1つの行に結合する

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 

私は各行を1行にまとめようとしています。今のところ、クエリは重複行だけを取得します。

何か提案がありがとうございます。

答えて

2

group byからTABLE.HOLDを削除してください。

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デモ:http://rextester.com/FPFI26814

リターン:

+-----+--------+------------+ 
| 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

は、行ごと、または一人あたりのユニークidですか?以下は関係なく、安全である:

明らか
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; 

HOLDGROUP BYから削除する必要がありますが、IDも同様に除去する必要がある場合があります。

関連する問題