Select p.prodCode,
p.description,
p.unit,
SUM(sd.quantity) "Total quantity"
FROM salesDetail sd
RIGHT JOIN product p
ON p.prodCode = sd.prodCode
GROUP BY p.prodCode
ORDER BY 4 DESC
帮助!我的脚本没有运行。我需要得到每个产品的总数量,但我的团队不起作用。
答案 0 :(得分:1)
计算单独子查询中每种产品的数量总和,然后将其连接回原来的product
表:
SELECT t1.prodCode,
t1.description,
t1.unit,
t2.total_quantity
FROM product t1
INNER JOIN
(
SELECT p.prodCode, SUM(sd.quantity) total_quantity
FROM product p
LEFT JOIN salesDetail sd
ON p.prodCode = sd.prodCode
GROUP BY p.prodCode
) t2
ON t1.prodCode = t2.prodCode
请注意,我通过切换子查询中连接表的顺序,将RIGHT JOIN
替换为LEFT JOIN
。
<强>更新强>
如果您绝对需要使用RIGHT JOIN
,那么只需将子查询替换为:
SELECT p.prodCode, SUM(sd.quantity) total_quantity
FROM salesDetail sd
RIGHT JOIN product p
ON p.prodCode = sd.prodCode
GROUP BY p.prodCode