开发者

TSQL Group By including all columns

I have a TSQL Query that does something like this:

SELECT SUM(s.Amount) as TotalSales, p.ProductName
FROM SALES s 
INNER JOIN Product p ON s.ProductID = p.ID
GROUP BY p.ProductName开发者_如何学JAVA

The resulting output is

TotalSales  Product
-----------------------
123.45      Apples
234.56      Oranges
345.67      Grapes

What I would like to do is get ALL the products in the results, even the ones that have no sales. I tried doing a LEFT JOIN on the product table, but that just confuses things.

So I would like my output to be something like this.

TotalSales  Product
-----------------------
123.45      Apples
234.56      Oranges
345.67      Grapes
0.0         Lemons
0.0         Grapefruit

Any idea how to do this?


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


With left join (more readeability):

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜