這個查詢給出所需的輸出:
with t1 as (select row_number() over (partition by grp order by elmnt) pos,
grp, elmnt from table1),
t2 as (select row_number() over (partition by grp order by elmnt) pos,
grp, elmnt from table2),
tx1 as (select pos, grp grp1, elmnt,
listagg(elmnt, ',') within group (order by pos)
over (partition by grp) list
from t1),
tx2 as (select pos, grp grp2, elmnt,
listagg(elmnt, ',') within group (order by pos)
over (partition by grp) list
from t2)
select distinct elmnt
from (select * from tx1 full join tx2 using (list, elmnt))
where grp1 is null or grp2 is null;
你可以很容易地改變它顯示列表,只是distinct list
取代distinct elmnt
。您的答案和我的查詢之間的差異是listagg
分析版本和過濾full join
而不是union
結合兩個not in
子句。 前兩個子查詢(t1
和t2
)只增加了pos
列,您在原始問題中未提供;-)也許這也可以使用minus
運算符完成。
測試數據和輸出:
create table table1 (grp number(3), elmnt varchar2(5));
insert into table1 values (1, 'ABC');
insert into table1 values (1, 'XYZ');
insert into table1 values (1, 'QBC');
insert into table1 values (2, 'xxx');
insert into table1 values (2, 'yyy');
insert into table1 values (3, 'uuu');
insert into table1 values (3, 'ddd');
create table table2 (grp number(3), elmnt varchar2(5));
insert into table2 values (99, 'XYZ');
insert into table2 values (99, 'QBC');
insert into table2 values (99, 'ABC');
insert into table2 values (78, 'xxx');
insert into table2 values (78, 'QQQ');
insert into table2 values (64, 'uuu');
insert into table2 values (65, 'ddd');
ELMNT
-----
uuu
QQQ
yyy
ddd
xxx
感謝您的替代的解決方案。我喜歡你的解決方案,爲什麼當組內的訂單應該以同樣的方式工作時,會產生組序列? –