SQL在count和group中使用CASE

时间:2014-07-08 15:55:47

标签: mysql sql aggregate-functions

我使用CASE对表格中的数据进行分类并对其进行计数,但结果并不准确

现场演示[here]

select DATE(date) as day, count(*),
count(distinct case when name = 'fruit' then 1 else 0 end) as fruits,
count(distinct case when name = 'vege' then 1 else 0 end) as vege,
count(distinct case when name = 'sweets' then 1 else 0 end) as sweets
from food
group by day
with rollup

我不确定问题是出在CASE还是出现在匹配=的字符串中,因为那里没有“甜食”。它还算1吗? 任何指示我都很感激

3 个答案:

答案 0 :(得分:11)

您的问题是COUNT计算的每个结果都不是NULL。在你的情况下,你正在使用:

COUNT(distinct case when name = 'sweets' then 1 else 0 end)

因此,当名称不是sweets时,它会计算0。此外,由于您使用DISTINCT,因此它只计算一个或两个值。您应该使用SUM或删除DISTINCTELSE 0

SELECT  DATE(date) as day, 
        COUNT(*),
        SUM(CASE WHEN name = 'fruit' THEN 1 ELSE 0 END) as fruits,
        SUM(CASE WHEN name = 'vege' THEN 1 ELSE 0 END) as vege,
        SUM(CASE WHEN name = 'sweets' THEN 1 ELSE 0 END) as sweets
FROM food
GROUP BY DAY
WITH ROLLUP

或者:

SELECT  DATE(date) as day, 
        COUNT(*),
        COUNT(CASE WHEN name = 'fruit' THEN 1 ELSE NULL END) as fruits,
        COUNT(CASE WHEN name = 'vege' THEN 1 ELSE NULL END) as vege,
        COUNT(CASE WHEN name = 'sweets' THEN 1 ELSE NULL END) as sweets
FROM food
GROUP BY DAY
WITH ROLLUP

Here is修改后的sqlfiddle。

答案 1 :(得分:2)

您无法按别名分组。你必须按表达式进行分组。

group by date(date)

答案 2 :(得分:-1)

您可以对别名进行分组:

SELECT 
     FROM_UNIXTIME(UnixTimeField, '%Y') AS 'Year'
     ,FROM_UNIXTIME(UnixTimeField, '%m') AS 'Month'

FROM table p

GROUP BY  Year, Month