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

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 LEFT JOIN question...

Author  Topic 

Charlie74
Starting Member

1 Post

Posted - 2013-07-08 : 11:06:19


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
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2013-07-08 : 11:10:34
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

52326 Posts

Posted - 2013-07-08 : 11:11:34
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
   

- Advertisement -