一周后搜索我无法写这个查询请帮帮我。 我有3个表购买, selles ,东西。 我想先分别汇总 purchase.quantity selles.quantity 字段,然后减去这两列 purchase.quantity selles.quantity 然后再购买GROUP BY .scale,stuff.name
我有这3张桌子
table purchase:
'id', 'invoice_id', 'stuff_id', 'quantity', 'scale', 'price'
table selles:
'id', 'selles_invoice_num', 'stuff_id', 'quantity', 'scale', 'price'
table stuff:
'id', 'name'
我有这个查询,但结果(数量)是错误的
SELECT sum(purchase.quantity) - sum(selles.quantity) as quantities,
purchase.scale,
stuff.name ,
stuff.id
FROM purchase,
selles,
stuff
where purchase.stuff_id = selles.stuff_id
and purchase.scale = selles.scale
and purchase.stuff_id = stuff.id
group by purchase.scale,
stuff.name
ORDER BY stuff.name ,
purchase.scale
答案 0 :(得分:0)
尝试使用内部联接
SELECT sum(pur.psum) - sum(sca.ssum) as quantities, p.scale, st.name , st.id FROM
stuff st INNER JOIN
(SELECT sum(p.quantity) as psum,p.scale,p.stuff_id FROM purchase p GROUP BY p.scale,p.stuff_id) pur
on pur.stuff_id = st.id INNER JOIN
(SELECT sum(s.quantity) as ssum,s.scale,s.stuff_id FROM scale s GROUP BY s.scale,s.stuff_id) sca
on sca.scale=pur.scale and sca.stuff_id=pur.stuff_id group by pur.scale, st.name ORDER BY st.name , pur.scale;