1

这是我用来查找给定年龄范围内有多少人的 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

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

也就是说我得到了:

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。

4

1 回答 1

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上的演示

于 2013-04-08T11:48:44.030 回答