Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Basic question on joining zero valued products
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Yak Posting Veteran

81 Posts

Posted - 04/29/2008 :  09:48:58  Show Profile  Reply with Quote
I have a query that needs to find all orders placed for a given month, sorted by category, however my query isn't returning categories that had zero products sold for the month. So my question is, just as an example, if I had three tables to find total order counts, but one of the products didn't sell any that month, how would I display it on the report?:
Table: Categories
CategoryID | CategoryName
1 | Cat1
2 | Cat2

Table: Products
ProductId | ProductName | ProductCategoryId
1 | Prod1 | 1
2 | Prod2 | 2

Table: Orders
OrderID | OrderDate | ProductID
1 | 4/18/2008 | 1
2 | 4/19/2008 | 1
3 | 4/23/2008 | 1


In this case, my results should be the "Cat1" category has 3 and the "Cat2" category has 0, however my query only displays "Cat1". Since "Cat2" has zero, it ignores it.

How would I setup my query to include "cat2" with its zero value as well?


Very Important crosS Applying yaK Herder

52326 Posts

Posted - 04/29/2008 :  10:42:34  Show Profile  Reply with Quote
SELECT c.CategoryID,
       SUM(CASE WHEN o.OrderID IS NULL THEN 0 ELSE 1 END) AS [Count]
FROM Categories c
INNER JOIN Products p
ON p.ProductCategoryId=c.CategoryID
LEFT JOIN Orders o
ON o.ProductID=p.ProductId
GROUP BY c.CategoryID
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000