SQL Only consider the values ​​indicated in each column

In SQL, I have a column called "response", and the value can be 1 or 2. I need to generate an SQL query that counts the numbers 1 and 2 for each month. I have the following request, 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`)
+3
source share
3 answers

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`)
+5
source

I met for a year, a month and, in addition, the answer itself. This will result in two lines per month: occurrence count for answer 1 and the other for answer 2 (it is also common for additional answer values)

SELECT MONTH(`date`), YEAR(`date`), answer, COUNT(*)
FROM results
GROUP BY YEAR(`date`), MONTH(`date`), answer
+6
source
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
0
source

Source: https://habr.com/ru/post/1709180/


All Articles