MySQL - 获取COUNT取决于值

时间:2014-05-23 04:34:12

标签: mysql sql

如何获取特定字段的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

感谢。很抱歉解释。 :)

1 个答案:

答案 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