2012-08-23 216 views
-1

我有两个表readysaleordersale。我想得到两个表的总和。表列如 t1=pid,branch,quantityt2=pid,branch,quantity。我需要分支列中所有分支的列表,并显示总金额为readysale,ordersale。 某些分公司他们没有做好销售准备或订购,但它应该显示在列表中0。总结两列

+1

请尽量说明一点。 – fancyPants

+0

请花一些时间来显示样本表和数据,如果你想让人们花时间在你的问题 – ClearLogic

回答

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
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); 
+0

谢谢你的回复,但我正在寻找像itemcode,brach,readysaleqty,ordersalequantity – user1453189

+0

@ user1453189好的,编辑好的列表。 –