三联表加减法

时间:2018-09-07 21:47:07

标签: sql join group-by

我有3张桌子(生产,销售,浪费)
所有3个表格均包含以下列:产品和数量
我需要一条查询语句,该语句将以以下方式连接所有3个表:

生产-销售-浪费

按产品分组

预先感谢您的提示和技巧:)

2 个答案:

答案 0 :(得分:0)

使用左联接合并表,按产品分组并通过减去值来获得总量,假设在销售或浪费表中没有给定产品的记录,然后将其计数为0。

select p.product, sum(p.quantity - coalesce(s.quantity,0) - coalesce(w.quantity,0)) as qty
from production p
left join sales s on p.product = s.product
left join wastage w on p.product = w.product
group by p.product

答案 1 :(得分:0)

您可以将每个表分别分组,然后[左]将它们加入:

SELECT p.product, p_quantity - COALESCE(s_quantity, 0) - COALESCE(w_quantity, 0)
FROM      (SELECT   product, SUM(quantity) AS p_quantity
           FROM     production
           GROUP BY product) p
LEFT JOIN (SELECT   product, SUM(quantity) AS s_quantity
           FROM     sales
           GROUP BY product) s ON p.product = s.product 
LEFT JOIN (SELECT   product, SUM(quantity) AS w_quantity
           FROM     wastage
           GROUP BY product) w ON p.product = w.product