我有两个表, Table_A 和 Table_B 。
我想要下面的结果结果,有人可以帮我解决SQL查询吗?
表-A
------------------
ID ITEM_ID QTY
------------------
1 100 2
2 101 3
3 102 5
4 103 2
------------------
表-B
------------------
ID ITEM_ID QTY
1 100 2
2 101 4
3 102 4
4 104 2
5 105 1
------------------
RESULT
------------------
ITEM_ID QTY
100 0
101 1
102 -1
103 -2
104 2
105 1
------------------
感谢。
答案 0 :(得分:1)
您需要完整联接才能从任一表中获取值
select
isnull(a.item_id,b.item_id) as item_id, isnull(b.qty, 0) - isnull(a.qty, 0) as qty
from
table_a a
full outer join table_b b on a.item_id = b.item_id
答案 1 :(得分:0)
select item_id, sum(qty)
from (select item_id, qty
from table_b
union all
select item_id, -qty
from table_a) x
group by item_id
order by item_id
答案 2 :(得分:0)
使用完全外连接和一些isnulls
select isnull(b.item_id, a.item_id) as ItemID,
isnull(b.qty, 0) - isnull(a.qty,0)as Qty
from table_b b
full outer join table_a a on a.item_id = b.item_id
order by itemid