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
 General SQL Server Forums
 New to SQL Server Programming
 LEFT JOIN question...
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Charlie74
Starting Member

1 Posts

Posted - 07/08/2013 :  11:06:19  Show Profile  Reply with Quote


Ok... I always struggle with LEFT JOINS for some reason in SQL.

I have a simple query


SELECT COUNT(*) as OpenedToday, c.Product_Line, c.Product_Code
FROM SFCase as c
LEFT OUTER JOIN (SELECT DISTINCT Product_Code from SFCase) as p ON p.Product_Code = c.Product_Code
GROUP BY c.Product_Line, c.Product_Code


What I'm expecting is a list of all Product_Code, with a count of how many cases were OpenedToday (including zero values). Instead, I only get a list of those product codes that have cases opened today (only positive values).

What am I doing wrong with this join?

Charlie

TG
Flowing Fount of Yak Knowledge

USA
5932 Posts

Posted - 07/08/2013 :  11:10:34  Show Profile  Reply with Quote
you need to start with the complete product code list then left outer join to the data that may or may not have cases. So you've got it backwards.

Be One with the Optimizer
TG
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52249 Posts

Posted - 07/08/2013 :  11:11:34  Show Profile  Reply with Quote
you had the wrong order of tables. the base table should come left

ie like

SELECT COUNT(*) as OpenedToday, c.Product_Line, c.Product_Code
FROM (SELECT DISTINCT Product_Code,Product_Line from SFCase) as c
LEFT OUTER JOIN SFCase as p ON p.Product_Code = c.Product_Code
GROUP BY c.Product_Line, c.Product_Code


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
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.03 seconds. Powered By: Snitz Forums 2000