2012-08-23 262 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好的,編輯好的列表。 –