2016-08-22 30 views
0

我有兩個不同的表中的樣本如下。我將不得不編寫一個sql來比較相同的源鍵綁定在一起。兩個表中的綁定鍵不匹配。比較組具有相同的綁定鍵

在下面的例子中,在表1中有3個綁定鍵1,3.綁定鍵1有3個成員連接到ABC,XYZ,& QBC。同樣綁定密鑰2 & 3每個都有2個源密鑰連接到它們。

在表2中,綁定密鑰99具有與表1相同的3個密鑰(計數和密鑰相同),而綁定密鑰78具有與表1的綁定密鑰2相同的計數,但它們的源密鑰是不同。綁定密鑰64具有1個源鍵和綁定密鑰65具有1

table 1: 
============================== 
Binding Key|source Key 
1|ABC 
1|XYZ 
1|QBC 
2|xxx 
2|yyy 
3|uuu 
3|ddd 

Table 2: 
========================== 
Binding Key|source Key 
99|XYZ 
99|QBC 
99|ABC 
78|xxx 
78|QQQ 
64|uuu 
65|ddd 

預期輸出是識別這並不匹配計數或源關鍵成員的基團。

Expected Output: 
=========================== 
xxx 
yyy 
uuu 
ddd 
QQQ 

很多感謝!

回答

1

我找到了解決方案。它在listagg函數的幫助下連接同一組內的字符串,然後進行比較。示例sql如下所示。

> SELECT * FROM (SELECT grp , 
>  ListAgg(elmnt, ',') within GROUP ( ORDER BY pos) AS list FROM table1 GROUP BY grp ) table1 WHERE table1.list NOT IN 
> (SELECT ListAgg(elmnt, ',') within GROUP ( ORDER BY pos) AS list 
> FROM table2 GROUP BY grp ) UNION SELECT * FROM (SELECT grp , 
>  ListAgg(elmnt, ',') within GROUP ( ORDER BY pos) AS list FROM table2 GROUP BY grp ) table1 WHERE table1.list NOT IN 
> (SELECT ListAgg(elmnt, ',') within GROUP ( ORDER BY pos) AS list 
> FROM table1 GROUP BY grp ) ; 
0

這個查詢給出所需的輸出:

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子句。 前兩個子查詢(t1t2)只增加了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 
+0

感謝您的替代的解決方案。我喜歡你的解決方案,爲什麼當組內的訂單應該以同樣的方式工作時,會產生組序列? –

相關問題