Getting Group By Count In Left Outer Join

Posted April 26, 2006 at 4:28 PM by Ben Nadel

Tags: SQL

Sometimes I amazed that I just miss the most obvious solutions. I was running a query that had a left outer join on a list of vendors, joining to orders (purchase orders). I wanted to get the count of orders per vendor, so I was just getting the COUNT(*) of the Group BY.

The problem with this technique is that the COUNT(*) counts the vendor in the left outer join, not just the orders in the right portion of the join. To solve this, I started to do crazy queries involving sub-queries. It was nuts. Then, it dawned on me... I DON'T have to do COUNT(*). I can do counts on specific columns. And hence:

SELECT

t.id,
t.name,
( ISNULL( COUNT(r.id), 0 ) ) AS reward_count,
( ISNULL( SUM(r.price), 0 ) ) AS price_sum,
( 0 ) AS reward_count_percent,
( 0 ) AS price_sum_percent

FROM

vendor_type t

LEFT OUTER JOIN

vendor_vendor_type_jn vtjn

ON

t.id = vtjn.vendor_type_id

LEFT OUTER JOIN

@reward r

ON

vtjn.vendor_id = r.vendor_id

GROUP BY

t.id,
t.name

 

As you can see, the COUNT() runs on r.id. This way, it can return a Type row with a count of zero. The only caveat is that you have to check for NULL values on the COUNT (and the SUM) since there might not be any records in the right portion of the JOIN.


You Might Also Be Interested In:



Reader Comments

Jun 6, 2007 at 10:56 AM // reply »
2 Comments

Wouldn't you only have to do the ISNULL for SUM? COUNT (at least on MSSQL) should have a count of 0 (zero) for NULL values.


Jun 6, 2007 at 11:52 AM // reply »
11,246 Comments

@Gareth,

You might be correct on that, cause COUNT() should return zero if there are no records. Good call.


Feb 11, 2008 at 1:41 AM // reply »
1 Comments

Thanks for this... I was also about to embark on a crazy sub-query journey.


Mar 21, 2008 at 12:26 PM // reply »
7 Comments

thanks for the code.


Apr 11, 2008 at 6:09 PM // reply »
1 Comments

Thank You!


Nov 1, 2008 at 7:46 PM // reply »
1 Comments

Hi Thanks for this Code!

LG from Austria


Mar 8, 2009 at 8:26 PM // reply »
1 Comments

Thanks!

It was had been a while since I last did this.. I forgot that I had to use group by to get all my listings :D


Mar 9, 2009 at 8:16 AM // reply »
11,246 Comments

@Blaine,

Glad to help out :)


Jun 18, 2009 at 7:29 PM // reply »
1 Comments

Thanks this helped a bunch. I was trying to count the comments associated to a topic, and I didn't want to run subqueries. BTW, for MySQL the command is IfNull


Sep 10, 2009 at 10:45 AM // reply »
1 Comments

Glad I came across your posting because it didn't dawn on me initially to do it this way either. Your post saved me from going down the crazy query road.

Thanks ...


Sep 10, 2009 at 10:50 AM // reply »
11,246 Comments

@Mike,

Glad to help.

@Ruddy,

Thanks for the MySQL tip. I used to do only MS SQL, but now, we use mostly MySQL at work, so that helps.


Sep 27, 2009 at 1:38 AM // reply »
1 Comments

rewrite the given query without using join and group by
select b.title,max(bc.returneddate-bc.checkoutdate) ''most days out'' from bookshelf_checkout bc,bookshelf b where bc.title(+)=b.title group by b.title;


Nov 14, 2009 at 2:10 AM // reply »
1 Comments

Thanks for the tip - I was stuck on this one too!


Nov 15, 2009 at 7:10 PM // reply »
11,246 Comments

@Jeff,

Glad to help.


Nov 19, 2009 at 3:52 PM // reply »
1 Comments

Thanks for this blog. I was stuck with the COUNT(*) when I really wanted to count only one column. It didn't even click to me until I visit your bolg.


May 14, 2010 at 10:51 AM // reply »
1 Comments

This SQL isn't syntatically correct as ISNULL() only takes 1 parameter. I would suggest something along the lines of:

IF( ISNULL( COUNT(r.id)), 0, COUNT(r.id) ) AS reward_count


May 16, 2010 at 9:39 PM // reply »
11,246 Comments

@George,

What SQL engine are you using? I definitely ran this code before it was posted and it worked just fine.


Jan 2, 2011 at 12:06 PM // reply »
1 Comments

It's been a rough four years ago since you've posted this, but it definitely works!

Thanks!


Jan 29, 2011 at 3:35 PM // reply »
1 Comments

Worked great. Thanks for the tip!


Feb 16, 2011 at 4:23 PM // reply »
1 Comments

@George,

That worked for me too



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 25, 2013 at 10:08 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
@Ben, my question is that i want the current node with its tag and its parent node. i just want only that data. So, give me the solution for that. and remember solution is working on " xpath 1.0 ... read »
May 25, 2013 at 10:01 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
hey ben, i want get my current node tag and also want the root node tag withing. So, how can i fix it.. ! ... read »
May 24, 2013 at 5:39 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Adam Oops! My mistake! I hadn't gotten that far in my testing - I'm still baby stepping my way through the process. ... read »
May 24, 2013 at 5:13 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
Hi Jason, Thanks for checking up on that, but I still stand firm on my position. :) There are actually two listLast()'s in use, and you're right that the one using a space as a delimiter is fine. ... read »
May 24, 2013 at 4:45 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Ben I have been lurking your site for quite some time, and haven't stepped up to comment until today. Thanks for all the great info - keep it up! @Adam I believe you are mistaken... as the commen ... read »
May 24, 2013 at 11:21 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, Ha ha, let's us never speak of justifying "##" notation again :P ... read »
May 24, 2013 at 11:18 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Ah, so it was indeed how I vaguely remembered it to be: A direct assignment value = users.id[ i ] causes value to retain the sticky datatype of the query column. Although unnecessary in ... read »
May 24, 2013 at 9:11 AM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Brandon, Hi, No, I haven't been able to do that. I have just kept it as it is. ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools