tags:

views:

19

answers:

3

So, coming up with a title for this is difficult

SELECT Date(p.born_at), SUM(p.value) as 'total_value_for_day'
FROM puppies as p
WHERE p.status = 2
GROUP BY DATE(p.born_at);

So, this gives a 2 column result.

What I want is this:

columns:

date | status = 1 | status = 2 | status = 3
DATA!!!

is there a way to do that?

+1  A: 
SELECT Date(born_at), 
    SUM(case when Status = 1 then value else 0 end) as 'status = 1',
    SUM(case when Status = 2 then value else 0 end) as 'status = 2',
    SUM(case when Status = 3 then value else 0 end) as 'status = 3' 
FROM puppies 
GROUP BY DATE(born_at); 
RedFilter
is it better to use the WHERE or not use the WHERE?
DerNalia
If you have more than 3 possible statuses, I would use a WHERE clause. It is unclear from your question...
RedFilter
(As Martin already said :) )
RedFilter
+1  A: 
SELECT Date(p.born_at), 
SUM(case when status = 1 then p.value end) as 'status = 1',
SUM(case when status = 2 then p.value end) as 'status = 2',
SUM(case when status = 3 then p.value end) as 'status = 3'
FROM puppies as p
WHERE p.status in(1,2,3)
GROUP BY DATE(p.born_at);
Martin Smith
is it better to use the WHERE or not use the WHERE?
DerNalia
Depends on your data! Using the `WHERE` will potentially avoid processing unnecessary rows if you have ones where status is not 1,2, or 3. If all of the rows have one of those values then it would probably be best to remove it to avoid a redundant check.
Martin Smith
+1  A: 
SELECT
   DATE(p.born_at)
   , SUM(CASE WHEN STATUS = 1 THEN p.value END) AS 'Status = 1'
   , SUM(CASE WHEN STATUS = 2 THEN p.value END) AS 'Status = 2'
   , SUM(CASE WHEN STATUS = 3 THEN p.value END) AS 'Status = 3'
FROM puppies AS p
WHERE p.status IN(1, 2, 3)
GROUP BY DATE(p.born_at);
dvanaria