当两个表中的一个表中没有行时,在sql j中连接两个具有不匹配行的表

时间:2012-11-14 14:17:05

标签: sql oracle-sqldeveloper

我有两张桌子,里面有售出的物品数量。我需要比较这两个表并获取不匹配的记录,一个表中销售的商品总数不等于其他表中销售的单位数量

select * from 
(select sum(units) AS UNITS, item, location, tran_date from tran_data_history where tran_date  = '' and tran_code = 1 group by item, location,tran_date)A,
(select sum(qty) AS QTY, item, store from sa_tran_item where  tran_Seq_no =''
)B
where A.item = B.item and A.location = B.store and A.UNITS <> B.QTY;

它给了我两个表中不匹配的项目数的行。但我想要那些项目,商店组合也存在于一个表中而不存在于另一个表中。

例如 tran_data_history

item location units
11     a        5
22      b        1
33      c        4

sa_tran_item

item  store  qty
11      a     4
33      c      4
在sa_tran_item中,项目33未发布,我想显示行

item  store  qty  units
11      a     4    5
22      b      0    1

请帮助

2 个答案:

答案 0 :(得分:0)

select * from 
(select sum(units) AS UNITS, item, location, tran_date from tran_data_history where tran_date  = '' and tran_code = 1 group by item, location,tran_date) A
    full outer join 
(select sum(qty) AS QTY, item, store from sa_tran_item where  tran_Seq_no ='')B
on A.item = B.item and A.location = B.store 
where A.UNITS <> B.QTY;

答案 1 :(得分:0)

我现在没有安装带有数据库的计算机,但看起来你想要进行全外连接。请参阅SQL JOIN维基百科条目的FULL OUTER JOIN部分。此代码应该可以满足您的要求:

select 
    * 
from 
    (
        select 
            sum(units) AS UNITS
            , item
            , location
            , tran_date 
        from 
            tran_data_history 
        where 
            tran_date  = '' 
            and tran_code = 1 
        group by 
            item
            , location
            ,tran_date
    )A
FULL OUTER JOIN
    (
        select 
            sum(qty) AS QTY
            , item
            , store 
        from 
            sa_tran_item 
        where  
            tran_Seq_no =''
    )B 
 ON
 A.item = B.item 
 and A.location = B.store
 and and A.UNITS <> B.QTY
/