GROUP BY idする必要があります 、および「複数の注文」の条件がHAVINGになります 句(入力データの個々の行ではなく、各グループに対する制約であるため)。集計はLISTAGGで行われます 。
with
test_data ( id, product, code ) as (
select 1, 'Apple' , 145 from dual union all
select 1, 'Grapes', 146 from dual union all
select 2, 'Orange', 147 from dual union all
select 2, 'Apple' , 145 from dual union all
select 2, 'Plum' , 148 from dual union all
select 3, 'Grapes', 146 from dual union all
select 3, 'Orange', 147 from dual union all
select 4, 'Grapes', 146 from dual union all
select 5, 'Orange', 147 from dual
)
-- End of test data (not part of the solution). Query begins below this line.
select id, listagg(code, ' | ') within group (order by id) as codes
from test_data
group by id
having count(*) > 1
;
ID CODE
-- ---------------
1 145 | 146
2 145 | 147 | 148
3 146 | 147
ただし、Oracle 10には、LISTAGG()がありません。 。 Oracle 11.2以前は、同じ結果を得る一般的な方法は、以下のような階層クエリを使用することでした。
select id, ltrim(sys_connect_by_path(code, ' | '), ' | ') as codes
from (
select id, code,
row_number() over (partition by id order by code) as rn
from test_data
)
where connect_by_isleaf = 1 and level > 1
connect by rn = prior rn + 1
and prior id = id
and prior sys_guid() is not null
start with rn = 1
;
編集済み :
同じIDに対して繰り返されるCODEを最初に「区別」する必要がある場合は、2番目のソリューションを使用して、最も内側のサブクエリで次の変更が必要です。
-
SELECT ID, CODE, ...を変更しますSELECTへDISTINCTID, CODE, ... -
ROW_NUMBER()を変更しますDENSE_RANK()へ