ELSE '60 +'不在CASE声明中工作,但ELSE'其他'工作

时间:2013-04-08 10:21:05

标签: mysql sql if-statement case

这是一个SQL语句,用于查找给定年龄段(百分比)中有多少人。

SELECT
CASE 
WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 10 THEN '-10' 
WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 20 THEN '11-20'
    WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 30 THEN '21-30'
    WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 60 THEN '31-60'
ELSE '60+' 
END AS Age, 
(Count(adherent_naissance)* 100 / (Select Count(*) From adherent)) as Pourcentage
FROM adherent
GROUP BY 
CASE 
WHEN Age <= 10 THEN '-10' 
WHEN Age <= 20 THEN '11-20'
    WHEN Age <= 30 THEN '21-30'
    WHEN Age <= 60 THEN '31-60'
ELSE '60+' 
END

一切正常,除非有人属于“Else”类别,然后我有一个奇怪的行为:此人被计入上一类。

也就是说我得到了:

Age     Pourcentage
11-20   33.3333
21-30   33.3333
31-60   33.3333

而不是:

Age     Pourcentage
11-20   33.3333
21-30   33.3333
31-60   16.6667
60+     16.6667

ELSE '60'也不起作用,但ELSE 'Others'确实有用......

有什么想法吗?谢谢!

注意(测试数据):SELECT adherent_naissance FROM adherent WHERE 1返回

adherent_naissance
1991-01-09
1990-03-28
1995-09-10
1964-01-10
1992-08-19
1920-02-21

如果有帮助,我使用的是MySQL 5.5.24-log。

1 个答案:

答案 0 :(得分:1)

您需要将相同的CASE表达式添加到GROUP BY子句

SELECT
CASE 
WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 10 THEN '-10' 
WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 20 THEN '11-20'
    WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 30 THEN '21-30'
    WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 60 THEN '31-60'
ELSE '60+' 
END AS Age, 
(Count(adherent_naissance)* 100 / (Select Count(*) From adherent)) as Pourcentage
FROM adherent
GROUP BY 
CASE 
WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 10 THEN '-10' 
WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 20 THEN '11-20'
    WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 30 THEN '21-30'
    WHEN FLOOR(DATEDIFF(NOW(), adherent_naissance)/365.4) <= 60 THEN '31-60'
ELSE '60+' 
END

SQLFiddle上的演示