我有一个TSQL查询,可以这样做:
SELECT SUM(s.Amount) as TotalSales, p.ProductName
FROM SALES s
INNER JOIN Product p ON s.ProductID = p.ID
GROUP BY p.ProductName
结果输出
TotalSales Product
-----------------------
123.45 Apples
234.56 Oranges
345.67 Grapes
我想要做的是获得结果中的所有产品,甚至是那些没有销售的产品。我尝试在产品表上进行LEFT JOIN,但这只会让事情变得混乱。
所以我希望我的输出是这样的。
TotalSales Product
-----------------------
123.45 Apples
234.56 Oranges
345.67 Grapes
0.0 Lemons
0.0 Grapefruit
知道怎么做吗?
答案 0 :(得分:4)
SELECT SUM(ISNULL(s.Amount,0)) as TotalSales, p.ProductName
FROM SALES s
RIGHT JOIN Product p ON s.ProductID = p.ID
GROUP BY p.ProductName
答案 1 :(得分:2)
SELECT COALESCE(SUM(s.Amount), 0) as TotalSales, p.ProductName
FROM Product p
LEFT JOIN SALES s ON s.ProductID = p.ID
GROUP BY p.ProductName
答案 2 :(得分:2)
使用左连接(更多可重复性):
SELECT SUM(ISNULL(s.Amount,0)) as TotalSales, p.ProductName
FROM Product p
LEFT JOIN SALES s ON p.ProductID = s.ID
GROUP BY p.ProductName