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 23, 2013 at 9:52 PM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Muhmmadibn Did you figure out a solution to launching PDFs? I am running into the same issues myself. There is no way to close the PDF or go back once you launch it. Thanks in advance! ... read »
May 23, 2013 at 6:06 PM
The Girl Who Broke My Heart, And Made Me A Better Person
Good day,ladies and gentle men, my name is Dr AMADI the great spell caster in Africa, i have help so many people for different kind of problems,who say there is no solution to problems on earth, that ... read »
May 23, 2013 at 4:26 PM
ColdFusion QueryAppend( qOne, qTwo )
@Heather, Glad people are still getting value out of this! ... read »
May 23, 2013 at 3:49 PM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, I meant the code at the bottom (not the video). I did try to experiment with an intermediary variable, like: value = users.id[ i ]; arrayContains( userIDs, value ); ... but t ... read »
May 23, 2013 at 11:06 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Are you talking about As Number: YES As String: YES As Java: YES? If so, that's with 3 different ways of referencing the constant 1, not users.id[1]. Query object references(*) are what seem ... read »
May 23, 2013 at 9:55 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Dan, According to the CF Admin, I'm running Java "1.6.0_45". As far as the DB column, in the database it's an INT. I'll see if I can dig into what CF sees it as. @WebManWalking, But h ... read »
May 23, 2013 at 9:49 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, I think the problem is that we're used to loose typing in ColdFusion, like JavaScript. If a value is a number but it's needed in an expression to be a string, noooo problem. I've encountered ... read »
May 23, 2013 at 9:47 AM
ColdFusion QueryAppend( qOne, qTwo )
You rock! Thank you, thank you, thank you!!! ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools