我有两张表readysale
和ordersale
。我想得到两张桌子的总和。表的列像
t1=pid,branch,quantity
和
t2=pid,branch,quantity
。我需要分支列中所有分支的列表,并显示readysale,ordersale
的总和数量。
有些分店他们没有准备或订购销售,但它应该在列表中显示为0。
答案 0 :(得分:1)
这将从两个表联合在一起的表的总数量按分支分组:
select sales.branch, sum(sales.quantity) as quantity
from (
select branch, quantity
from readysale
union
select branch, quantity
from ordersale
) as sales
group by sales.branch
答案 1 :(得分:1)
select sum(u.quantity) as total, u.branch
from (
select quantity, branch
from readysale
union
select quantity, branch
from ordersale
) as u
group by u.branch
编辑:
然后
select u.itemcode, u.branch, sum(u.ordersaleqty), sum(u.readysaleqty)
from (
select itemcode, branch, 0 as ordersalqty, quantity as readysaleqty
from readysale
union
select itemcode, branch, quantity as ordersalqty, 0 as readysaleqty
from ordersale
) as u
group by u.itemcode, u.branch
或使用完整的外部联接
select
coalesce(r.itemcode, o.itemcode),
coalesce(r.branch, o.branch),
sum (r.quantity) as readysaleqty,
sum (o.quantity) as ordersaleqty
from readysale r
full outer join ordersale o on o.branche = r.branch
group by coalesce(r.itemcode, o.itemcode), coalesce(r.branch, o.branch);