SQL语句where子句按年龄组

时间:2015-02-02 01:21:56

标签: mysql select where

在尝试使用SQL语句根据每个年龄组获取年龄时遇到了一些问题。

我的帐户表 enter image description here

我将ageDate存储在此表中。然后我运行这个SQL语句来获得年龄:

SELECT count(be.eventID) ,TIMESTAMPDIFF(YEAR, str_to_date(a.birthDate,'%d/%m/%Y'), CURDATE()) AS age, a.gender, be.eventID
FROM account a INNER JOIN bookedevent be ON be.bookedEventBy = a.accountName
WHERE a.gender = 'M'
GROUP BY be.eventID
ORDER BY count(be.eventID) DESC

但是使用这个SQL,我不知道我应该如何按年龄组进行where子句。假设有年龄组1-10,11-20,21-30,31-40,41-50和50及以上。有了这个SQL,我得到了这个结果:

enter image description here

从这里你可以看到,有一个2属于另一个年龄组,11-20岁。我想知道是否可以使用SQL语句区分年龄组?

1 个答案:

答案 0 :(得分:0)

使用Between运算符过滤两个值之间的结果。

SELECT Count(be.eventID),
       Timestampdiff(YEAR, Str_to_date(a.birthDate, '%d/%m/%Y'), Curdate()) AS age,
       a.gender,
       be.eventID
FROM   account a
       INNER JOIN bookedevent be
               ON be.bookedEventBy = a.accountName
WHERE  a.gender = 'M'
       AND Timestampdiff(YEAR, Str_to_date(a.birthDate, '%d/%m/%Y'), Curdate()) 
           BETWEEN 11 AND 20 -- Here you can define the range to be filtered
GROUP  BY be.eventID
ORDER  BY Count(be.eventID) DESC