我有两张桌子
ITEMLOC:
ITEM LOC STOCK
ORDERS:
ORDNO ITEM LOC QTY
我希望看到以下结果:
ITEM LOC SUMofOrderQty SUMofStock
如何从两个表中获取聚合以比较商品和位置上的Stock和OrderedQty
答案 0 :(得分:1)
SELECT l.item,
l.loc,
l.sum_of_stock,
o.sum_of_qty
FROM (
SELECT item, loc, SUM( stock ) AS sum_of_stock
FROM item_loc
GROUP BY item, loc
) l
INNER JOIN
(
SELECT item, loc, SUM( qty ) AS sum_of_qty
FROM orders
GROUP BY item, loc
) o
ON ( l.item = o.item AND l.loc = o.loc )
WHERE l.sum_of_stock >= o.sum_of_qty
答案 1 :(得分:0)
Select a.ITEM, a.LOC, a.SUMofOrderQty, SUMofStock from
(Select ITEM LOC , Sum ( QTY)
FROM ORDERS
ITEM, LOC
) a,
(Select ITEM, LOC , Sum (STOCK)
FROM ITEMLOC
group by ITEM, LOC ,
) b
Where a.ITEM=b.ITEM
AND b.LOC= a.LOC
抱歉打字错误
答案 2 :(得分:0)
另一种方式
Select ITEM, LOC, SUM(q),SUM(s)
FROM (
Select ITEM , LOC , 0 q ,STOCK s
FROM ITEMLOC
Union
SELECT ITEM ,LOC, QTI q ,0 s
FROM ORDERS)
group by ITEM ,LOC
ITEM LOC必须是主键
如果不是:
Select ITEM, LOC, SUM(q),SUM(s)
FROM (
Select ITEM , LOC , 0 q ,sum(STOCK) s
FROM ITEMLOC
group by ITEM ,LOC
Union
SELECT ITEM ,LOC, sum(QTI) q ,0 s
FROM ORDERS
group by ITEM ,LOC)
group by ITEM ,LOC