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 »
10,640 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 »
10,640 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 »
10,640 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 »
10,640 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 »
10,640 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
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »