我在计算MySQL用户的年龄,我遇到了一个小问题。我能够成功计算每个用户的年龄,但是,当我尝试计算每个年龄组的用户数时,就是我遇到麻烦的时候。这是我的疑问:
SELECT COUNT(user_id) AS "Number of Users",
YEAR(CURDATE()) -
YEAR(STR_TO_DATE(birth_date, '%m/%d/%Y')) -
(RIGHT(CURDATE(), 5) < RIGHT(STR_TO_DATE(birth_date, '%m/%d/%Y'), 5))
AS Age
FROM user
GROUP BY Age
我觉得我很亲密,只是不适合我。我如何计算每个年龄段的用户数量?
答案 0 :(得分:2)
您需要一个子查询来访问Group By
子句
SELECT Age,COUNT(user_id) AS "Number of Users"
FROM
(
SELECT userid,
YEAR(CURDATE()) -
YEAR(STR_TO_DATE(birth_date, '%m/%d/%Y')) -
(RIGHT(CURDATE(), 5) < RIGHT(STR_TO_DATE(birth_date, '%m/%d/%Y'), 5))
AS Age
FROM user
) as Z
GROUP BY Age