tags:

views:

469

answers:

3

In sql i have a column called answer and it can either be 1 or 2, i need to generate an SQL query which counts the amount of one and twos for each month, i have the following query but it does not work:

SELECT MONTH(`date`), YEAR(`date`),COUNT(`answer`=1) as yes,
COUNT(`answer`=2) as nope,` COUNT(*) as total

FROM results

GROUP BY YEAR(`date`), MONTH(`date`)

Hope someone can help thanks in advanced!

+4  A: 

Try the SUM-CASE trick:

SELECT 
    MONTH(`date`), 
    YEAR(`date`),
    SUM(case when `answer` = 1 then 1 else 0 end) as yes,
    SUM(case when `answer` = 2 then 1 else 0 end) as nope,
    COUNT(*) as total
FROM results
GROUP BY YEAR(`date`), MONTH(`date`)
Andomar
the right idea, but the possible values are 1 and 2, not 1 and 0
Jonathan Fingland
Thanks, edited.
Andomar
A variation of this is to use count(distinct case when `answer`=1 then `answer`else null end). It is more useful when you have joins that will make the same rows appear more than once and you have a distinct value in answer (using sum(1) will add it several times for the same master row). Not useful in this case, but worth mentioning :)
Jimmy Stenke
+6  A: 

I would group by the year, month, and in addition the answer itself. This will result in two lines per month: one counting the appearances for answer 1, and another for answer 2 (it's also generic for additional answer values)

SELECT MONTH(`date`), YEAR(`date`), answer, COUNT(*)
FROM results
GROUP BY YEAR(`date`), MONTH(`date`), answer
Roee Adler
Same idea as I had. I'm sure it's also faster.
Georg
Nice idea, though this would not return the total count
Andomar
@Andomar: from the question - "i need to generate an SQL query which counts the amount of one and twos for each month". He did not mention anything about counting the total (although it does appear in his query, I suspect it's just because it's "easy"). Counting the total is not a big challenge, simply remove the "answer" from the GROUP BY and from the SELECT.
Roee Adler
A: 
SELECT year,
       month,
       answer
       COUNT(answer) AS quantity
FROM results
GROUP BY year, month, quantity
year|month|answer|quantity
2001|    1|     1|     2
2001|    1|     2|     1
2004|    1|     1|     2
2004|    1|     2|     2
SELECT * FROM results;
year|month|answer
2001|    1|     1
2001|    1|     1
2001|    1|     2
2004|    1|     1
2004|    1|     1
2004|    1|     2
2004|    1|     2
Georg