-1

我有两张桌子readysaleordersale. 我想得到两个表的总和。表格的列 t1=pid,branch,quantityt2=pid,branch,quantity.我需要分支列中所有分支的列表并显示.的总和数量readysale,ordersale。一些分店他们没有准备好或订购,但它应该在列表中显示为 0 。

4

2 回答 2

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
于 2012-08-23T13:44:44.493 回答
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);
于 2012-08-23T13:44:57.883 回答