迭代计数和where子句

时间:2017-11-23 19:25:29

标签: mysql

我需要一些帮助。 我有很多用户的出生日期:

SELECT COUNT(or SUM) ()    FROM ()

WHERE () = ''  

AND TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE())=18(age)

我必须通过仅更改where子句中的年龄来多次计算计数,总和,平均值以及列的这些内容。 我怎样才能确保我不浪费时间运行查询这么多年? 我必须从18岁到65岁:

SELECT COUNT(or SUM) () FROM ()

WHERE () = ''  AND () = ''

AND ()<'' 

AND TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE())=**19,29,21 etc**.

I would like this columns results:

count()  18

count()  19 etc

or

sum () 18

sum() 19 etc 

非常感谢你。

1 个答案:

答案 0 :(得分:0)

TIMESTAMPDIFF的结果作为列返回,然后使用GROUP BY

SELECT TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) AS age, COUNT(*)
FROM ...
WHERE ...
GROUP BY age