Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL SELECT SUM() BY DATE IF NO MATCH RETURN 0

I have connected three tables to each other. I'm querying keywords + statistics.

I need to get data out by date range, and if there is no data for that specific date range i would like it to return 0 statistics

Lets say my query is:
SELECT keyword,SUM(stat) FROM keywords WHERE date >='2012-07-10' GROUP BY keyword;

It would return
|my keyword 1|3|
|my keyword 2|6|

Example table content:
| id | keyword          | stat | date            | keywordGroup |
| 1  | my keyword 1 | 2     | 2012-07-11 | 1 |
| 2  | my keyword 1 | 1     | 2012-07-12 | 1 |
| 3  | my keyword 2 | 6     | 2012-07-11 | 1 |
| 4  | my keyword 3 | 10   | 2012-07-09 | 1 |

But there are some keywords which have no stats for that date range
but I would still like to get those keywords showing 0 as stats.

Like this:

|my keyword 1|3|
|my keyword 2|6|
|my keyword 3|0|

The problem is that the where clause blocks values that are not found, is there a workaround.
As I said I have three tables with relations, I use LEFT JOIN to query data, for simplification I left that part out of my example query.

Table: Campaigns
id
name

Table: KeywordGroup
id
name
campaign

Table: KeywordData
id
keyword
stat
date
keywordGroup

like image 929
Jompper Avatar asked Jan 28 '26 08:01

Jompper


2 Answers

Assuming you are joing tables with left joins correctly, use:

select keyword, ifnull(sum(stat),0) ... group by keyword

If it is WHERE clause that filters out some stats before even grouping is applied, then you need to move the date condition into LEFT JOIN condition, ie.

from KeywordGroup left join KeywordData on ... and date > '2012-07-10'

But I cannot help further without seeing actual queries. :-)

like image 84
Kuba Wyrostek Avatar answered Jan 29 '26 22:01

Kuba Wyrostek


Try this

select 
    t1.keyword,
    sum(t2.stat) as stat
from
(   
    select distinct keyword from keywords   
) as t1 left join
(
    SELECT keyword,SUM(stat) FROM keywords WHERE date >='2012-07-10' GROUP BY keyword
) as t2
on t1.keyword=t2.keyword;
like image 44
Madhivanan Avatar answered Jan 29 '26 22:01

Madhivanan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!