在 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`)
我会按年份、月份以及答案本身进行分组。这将导致每月两行:一个计算答案 1 的出现,另一个计算答案 2(对于其他答案值也是通用的)
SELECT MONTH(`date`), YEAR(`date`), answer, COUNT(*)
FROM results
GROUP BY YEAR(`date`), MONTH(`date`), answer
尝试 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`)
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