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
 Record Count

Author  Topic 

evanburen
Posting Yak Master

167 Posts

Posted - 2009-11-03 : 16:15:58
I don't understand why this code returns a count value for every user in the EDUsers table even when the count is zero

SELECT COUNT(dbo.Requests.ID) AS TotalOpenByEDUser
FROM dbo.Requests RIGHT OUTER JOIN
dbo.EDUsers ON dbo.Requests.UserID = dbo.EDUsers.UserID
WHERE dbo.Requests.DateClosed IS NULL
GROUP BY dbo.EDUsers.Username, dbo.EDUsers.UserID, dbo.Requests.DateClosed
ORDER BY dbo.EDUsers.Username

but this one does not. It only gives me the count for every user where the count is > 0

SELECT COUNT(dbo.Requests.ID) AS TotalClosedByEDUser
FROM dbo.Requests RIGHT OUTER JOIN
dbo.EDUsers ON dbo.Requests.UserID = dbo.EDUsers.UserID
WHERE dbo.Requests.DateClosed IS NOT NULL
GROUP BY dbo.EDUsers.Username, dbo.EDUsers.UserID, dbo.Requests.DateClosed
ORDER BY dbo.EDUsers.Username

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-11-03 : 16:18:04
That's how OUTER JOINs work. Even though the data is not null in the outer table, SQL Server will put NULL for the columns in the outer table where there weren't matches to the inner table.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2009-11-03 : 16:18:25
because you're doing a RIGHT JOIN?



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-11-03 : 16:41:20
Just to be clear, it would work the same with a LEFT JOIN too. It's just how outer joins work.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page

evanburen
Posting Yak Master

167 Posts

Posted - 2009-11-03 : 18:46:45
Is there any way to output a value of zero for the rest of the records in the second example?
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-11-03 : 23:30:43
Could you show us a data example to make it more clear?

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page
   

- Advertisement -