我有三个表:产品,销售和购买。
我需要获取产品的销售总额和购买总额。 即使未进行任何销售,我也需要显示购买的商品,反之亦然。 像这样:
Product | Sum of sales | Sum of purchases |
____________________________________________
product 1 | 10000 | 45000 |
product 2 | 20000 | 0 (or null) |
product 3 | 0(or null) | 20000 |
我已经尝试过了,但是它只会退回同时具有销售和购买功能的产品:
select prod.name, sum(s.total), sum(p.total)
from product prod
inner join sale s on s.prod_id = prod.id
inner join purchase p on p.prod_id = prod.id
group by 1;
谢谢。
答案 0 :(得分:0)
您的查询有两个问题。首先,由于INNER JOIN
,它将(如您所见)仅返回具有销售和购买的产品的值。可以通过使用LEFT JOIN
(带有可选的COALESCE
将null
值转换为0
)来解决。第二个问题是,您将在JOIN
中获得重复的行,其中有不止一种产品的销售或购买。要解决此问题,您需要在派生表中进行销售和购买汇总:
SELECT pr.name,
s.total AS sales, -- will show null if no sales
COALESCE(p.total, 0) AS purchases -- will show 0 if no purchases
FROM product pr
LEFT JOIN (SELECT prod_id, SUM(total) AS total
FROM sale
GROUP BY prod_id) s ON s.prod_id = pr.id
LEFT JOIN (SELECT prod_id, SUM(total) AS total
FROM purchase
GROUP BY prod_id) p ON p.prod_id = pr.id