[英]SQL; Only count the values specified in each column
In SQL I have a column called "answer", and the value can either be 1 or 2. I need to generate an SQL query which counts the number of 1's and 2's for each month. 在SQL中我有一个名为“answer”的列,值可以是1或2.我需要生成一个SQL查询,它计算每个月的1和2的数量。 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`)
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)
这将导致每月两行:一行计算答案1的外观,另一行计算答案2(它对于其他答案值也是通用的)
SELECT MONTH(`date`), YEAR(`date`), answer, COUNT(*)
FROM results
GROUP BY YEAR(`date`), MONTH(`date`), answer
Try the SUM-CASE trick: 尝试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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.