SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

Goalie35
Yak Posting Veteran

78 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?

Thanks.

visakh16
Very Important crosS Applying yaK Herder

India
52325 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  
 New 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.05 seconds. Powered By: Snitz Forums 2000