Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count data as zero if it is null when where clause is used

Tags:

sql

postgresql

Now I have this query:

SELECT 
opp.name as name,
count(log.stage_id) as stage_count
FROM 
crm_lead as opp LEFT OUTER JOIN crm_lead_stage_log as log ON (opp.id = log.opportunity_id)
GROUP BY
name

And it outputs this result:

name  | stage_count |
name1 | 2
name2 | 1
name3 | 0 

And it outputs what I need. But if I put any condition to it, then it skips rows with zero count, which I need to be able to see. For example if I write this query:

SELECT 
opp.name as name,
count(log.stage_id) as stage_count
FROM 
crm_lead as opp LEFT OUTER JOIN crm_lead_stage_log as log ON (opp.id = log.opportunity_id)
WHERE WHEN log.create_date > '2014-01-28 08:49:03'
GROUP BY
name

Then it outputs this:

name  | stage_count |
name1 | 1

It counts existing stages number in that time interval correctly, but it skips rows which stages number is not existing in the time inerval. How can I make it output like this (in that example only one stage for first row is counted in that time interval with new query, for other rows, it counts zero, because it does not exist):

name  | stage_count |
name1 | 1
name2 | 0
name3 | 0 

Is it possible to do it like that? P.S. if more information is needed, like to put this query sample online to check it out, just write a comment and I will update my answer).

like image 717
Andrius Avatar asked Jan 28 '14 12:01

Andrius


People also ask

Does COUNT work with NULL values?

The COUNT() function is used to obtain the total number of the rows in the result set. When we use this function with the star sign it count all rows from the table regardless of NULL values.

Does 0 COUNT as NULL?

The answer to that is rather simple: a NULL means that there is no value, we're looking at a blank/empty cell, and 0 means the value itself is 0. Considering there is a difference between NULL and 0, the way Tableau treats these two values therefore is different as well.

How do I COUNT NULL values in SQL?

Here's the simplest way to count NULL values in SQL The easiest way to count the NULLs in a column is to combine COUNT(*) with WHERE <column name> IS NULL .


1 Answers

Your where condition on the outer joined table turns the outer join into an inner join (because the "non-existing rows will have a NULL value and the comparison of NULL with something else yields "undefined" and thus will remove that row from the result)

You need to move that condition into the join condition:

SELECT opp.name as name,
       count(log.stage_id) as stage_count
FROM crm_lead as opp 
  LEFT JOIN crm_lead_stage_log as log 
         ON opp.id = log.opportunity_id
        AND log.create_date > '2014-01-28 08:49:03'
GROUP BY name;
like image 65
a_horse_with_no_name Avatar answered Oct 23 '22 19:10

a_horse_with_no_name