如何获取特定字段的COUNT()取决于字段的值?例如,我有字段typeOfAssistance
,在下面的查询中,我得到了typeOfAssistance
的总数,但我有不同的值,financial
medical
和{{ 1}},如何添加自定义列,除以总值取决于值?
burial
期望的输出:
SELECT date,COUNT(*) AS num
FROM requests
WHERE date BETWEEN DATE_ADD(CURDATE(),INTERVAL -20 DAY) AND CURDATE()
GROUP BY date
感谢。很抱歉解释。 :)
答案 0 :(得分:4)
通常情况下,我会使用SUM
而不是COUNT
来表示项目细分。
像
这样的东西SELECT date,
SUM(CASE WHEN typeOfAssistance = 'financial' THEN 1 ELSE 0 END) AS financial,
SUM(CASE WHEN typeOfAssistance = 'burial' THEN 1 ELSE 0 END) AS burial,
SUM(CASE WHEN typeOfAssistance = 'medical' THEN 1 ELSE 0 END) AS medical,
COUNT(1) AS Total
FROM requests
GROUP BY date