0

好吧,假设我有这个生日列表

在此处输入图像描述

我想计算具有相应年龄的数据,例如,

ages 10 - 15
ages 16 - 20
ages 21 - 30
and so on...

好吧,我从这个网站找到了这段代码

SELECT * 
FROM your_table 
WHERE YEAR(CURDATE())-YEAR(BirthDate) BETWEEN 10 AND 20;

这实际上有帮助,但是,我将如何通过使用多个 where 子句来应用它?

猜测代码表示

"SELECT COUNT(birthday) a IN (SELECT birthday FROM WHERE YEAR(CURDATE())-YEAR(BirthDate) BETWEEN 10 AND 15), COUNT(birthday) b IN (SELECT birthday FROM WHERE YEAR(CURDATE())-YEAR(BirthDate) BETWEEN 16 AND 20) FROM table"

那么如果我回应它,​​它会导致

Total result of age 10 - 15 : **25**

Total result of age 16 - 20 : **12**

有这样的吗?任何帮助,将不胜感激。

4

1 回答 1

2

这适用于 MySQL:

SELECT AGE_RANGE, COUNT(*) FROM (
    SELECT CASE
        WHEN YearsOld BETWEEN 0 AND 5 THEN '0-5'
        WHEN YearsOld BETWEEN 6 AND 10 THEN '6-10'
        WHEN YearsOld BETWEEN 11 AND 15 THEN '11-15'
        WHEN YearsOld BETWEEN 16 AND 20 THEN '16-20'
        WHEN YearsOld BETWEEN 21 AND 30 THEN '21-30'
        WHEN YearsOld BETWEEN 31 AND 40 THEN '31-40'
        WHEN YearsOld > 40 THEN '40+'
        END AS 'AGE_RANGE'
        FROM (
            SELECT YEAR(CURDATE())-YEAR(DATE(birthdate)) 'YearsOld' 
            FROM MyTable
        ) B
) A
GROUP BY AGE_RANGE
于 2013-06-27T04:15:32.440 回答