我只想在我的3桌中得到结果。首先,它将汇总每个商品代码的数量。然后根据我的公式输出结果。
SUM(table 1)
itemcode qty date
001 20 06-17
002 20 06-17
001 10 06-18
+(add) of
SUM(table 2)
itemcode qty date
001 10 06-17
002 40 06-17
001 5 06-18
-(subtract) of
table 3
itemcode qty date
001 5 06-17
002 5 06-17
002 5 06-18
结果:
itemcode qty
001 40
002 50
答案 0 :(得分:2)
使用以下查询
select t.itemcode as itemcode,sum(t.qty) as qty
from (
select itemcode,qty from table1
union all
select itemcode,qty from table2
union all
select itemcode,(qty * -1) from table3) as t
group by t.itemcode
答案 1 :(得分:1)
这里你去:) http://www.sqlfiddle.com/#!9/ce1d25/1/0
select TsumaTotal.itemcode, suma-resta from
(select Tsuma.itemcode,SUM(Tsuma.suma) as suma from
(select tb1.itemcode, SUM(tb1.qty) as suma from Table1 as tb1 group by tb1.itemcode
UNION
select tb2.itemcode, SUM(tb2.qty) as suma from Table2 as tb2 group by tb2.itemcode) as Tsuma
group by Tsuma.itemcode) as TsumaTotal right join
(select tb1.itemcode, SUM(tb1.qty) as resta from Table3 as tb1 group by tb1.itemcode) as Tresta
on TsumaTotal.itemcode = Tresta.itemcode;