私は2つのテーブルreadysale
とordersale
. 2つのテーブルの合計を取得したい。t1=pid,branch,quantity
と
のようなテーブルの列
t2=pid,branch,quantity
。支店の列にすべての支店のリストが必要で、の合計数量を表示しreadysale,ordersale
ます。一部のブランチでは、販売の準備ができていないか注文されていませんが、リストには 0 で表示されます。
2 に答える
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 に答える
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 に答える