2016-08-02 82 views
0

內的記錄我有一個表像下面:的Oracle SQL比較表

S.No | Item_ID | Item_Revision | Code | 
-----+---------+---------------+------- 
1. | item1 | 0    | xyz | 
2. | item2 | 0    | xyz | 
3. | item3 | 0    | xyz | 
4. | item1 | 1    |  | 
5. | item2 | 1    | abc | 
6. | item3 | 1    | xyz | 

我需要記錄比較表中找到的物品的不同版本代碼的差異。

我想要的結果設置如下:

| Item_ID | Code_Revision_0 | Code_Revision_1 | 
| item1 | xyz    |     | 
| item2 | xyz    | abc    | 

我不能制定一個Oracle查詢用於這一目的。

在此先感謝!

回答

1

一個基本思想是用join

select t0.item_id, t0.code as code_0, t1.code as code_1 
from t t0 join 
    t t1 
    on t0.item_id = t1.item_id and 
     t0.item_revision = 0 and 
     t1.item_revision = 1 
where t0.code <> t1.code; 

但是,如果code值爲NULL(或空字符串),你需要更加小心:

where t0.code <> t1.code or (t0.code is null and t1.code is not null) or 
     (t0.code is not null and t1.code is null) 
+0

即使我正在使用vkp的查詢,我將其標記爲答案。因爲你的解釋讓我明白vkp的查詢。謝謝! –

1

您可以使用自加入來執行此操作。

select t1.item_id, t1.code code_rev_0, t2.code code_rev_1 
from tablename t1 
join tablename t2 on t1.item_id=t2.item_id 
and t1.item_revision = 0 and t2.item_revision = 1 
where nvl(t1.code,'a') <> nvl(t2.code,'a') 
+1

的NVL伎倆在'where'條款,最好避免。除了明顯的('a'可能是'code'列中的一個合法值),這個技巧隱藏了這個意圖 - 如果其他數據庫專業人員將來需要維護或修改代碼,他們會更容易理解代碼(如果需要,也許可以修改它),如果它完全按照Gordon的規定寫出來的話。 (我的解決方案也做了同樣的事情,但戈登在我面前展示了正確的方式。)乾杯! – mathguy

1

這是一個使用PIVOT運算符而不是自連接的解決方案。如果我正確讀取執行計劃,則對於您提供的輸入數據而言,這會稍微高效(對於加入解決方案,成本爲13比17)。您可能想要根據您的實際數據測試兩種解決方案,以查看哪項更好。

with 
    input_data (item_id, item_revision, code) as (
     select 'item1', 0, 'xyz' from dual union all 
     select 'item2', 0, 'xyz' from dual union all 
     select 'item3', 0, 'xyz' from dual union all 
     select 'item1', 1, '' from dual union all 
     select 'item2', 1, 'abc' from dual union all 
     select 'item3', 1, 'xyz' from dual 
    ) 
select * 
from input_data 
pivot (max(code) for item_revision in (0 as code_revision_0, 1 as code_revision_1)) 
where code_revision_0    != code_revision_1 
    or code_revision_0 is  null and code_revision_1 is not null 
    or code_revision_0 is not null and code_revision_1 is  null 
; 

輸出

ITEM_ CODE_REVISION_0 CODE_REVISION_1 
----- ---------------- ---------------- 
item1 xyz 
item2 xyz    abc 

2 rows selected.