3

在 SQL 中,我有一个名为“answer”的列,其值可以是 1 或 2。我需要生成一个 SQL 查询来计算每个月 1 和 2 的数量。我有以下查询,但它不起作用:

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`)
4

3 回答 3

6

我会按年份、月份以及答案本身进行分组。这将导致每月两行:一个计算答案 1 的出现,另一个计算答案 2(对于其他答案值也是通用的)

SELECT MONTH(`date`), YEAR(`date`), answer, COUNT(*)
FROM results
GROUP BY YEAR(`date`), MONTH(`date`), answer
于 2009-05-27T11:53:45.727 回答
5

尝试 SUM-CASE 技巧:

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`)
于 2009-05-27T11:43:38.993 回答
0
SELECT year,
       month,
       answer
       COUNT(answer) AS quantity
FROM results
GROUP BY year, month, quantity
年|月|答案|数量
2001| 1| 1| 2
2001| 1| 2| 1
2004| 1| 1| 2
2004| 1| 2| 2
SELECT * FROM results;
年|月|答案
2001| 1| 1
2001| 1| 1
2001| 1| 2
2004| 1| 1
2004| 1| 1
2004| 1| 2
2004| 1| 2
于 2009-05-27T11:58:41.083 回答