Question

I think this is probably really easy but im not practiced in SQL and dont know much of the syntax.

Basically I got a big table with different User Complaints (represented by a problem ID) and Timestamps that I want to graph.

The individual statements are really easy and straightforward. Example:

SELECT DATE( datetimebegin ) AS Date, COUNT( * ) AS CntProb1
FROM `problems` 
WHERE problemID = "1"
GROUP BY Date, problemID;

SELECT DATE( datetimebegin ) AS Date, COUNT( * ) AS CntProb2
FROM `problems` 
WHERE problemID = "2"
GROUP BY Date, problemID;

Each Table gives me a pretty simple output:

Date, CntProb1
2013-03-11,4
2013-03-14,1
2013-03-17,7

Date, CntProb2
2013-03-12,2
2013-03-13,1
2013-03-14,3
2013-03-17,1

I need the result combined like this:

Date, CntProb1, CntProb2
2013-03-11,4,0
2013-03-12,0,2
2013-03-13,0,1
2013-03-14,1,3
2013-03-17,7,1

I guess this is something really simple if you know the right SQL Syntax... Some kind of Join?!

Any help is really appreciated!

Was it helpful?

Solution

You don't need a JOIN to get the result, you should be able to get it by using a CASE expression inside of your aggregate function:

SELECT 
    DATE(datetimebegin) AS Date, 
    sum(case when problemID = '1' then 1 else 0 end) AS CntProb1,
    sum(case when problemID = '2' then 1 else 0 end) AS CntProb2
FROM `problems` 
WHERE problemID in ('1', '2')
GROUP BY DATE(datetimebegin);

If you want to use count() instead of sum() then you would use:

SELECT 
    DATE(datetimebegin) AS Date, 
    count(case when problemID = '1' then problemID end) AS CntProb1,
    count(case when problemID = '2' then problemID end) AS CntProb2
FROM `problems` 
WHERE problemID in ('1', '2')
GROUP BY DATE(datetimebegin);

See SQL Fiddle with Demo of both queries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top