2016-08-02 133 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.