检索和计数没有。在一个查询中,具有多个WHERE子句的birthdate到Age的行?

时间:2013-06-27 04:02:13

标签: sql

好吧,让我说我有这个生日列表

enter image description here

我想用相应的年龄计算数据,

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**

有类似的东西吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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