简体   繁体   English

MySQL查询以计算年龄组中的用户数

[英]MySQL query to Count Number of Users in Age Group

I am calculating the age of my users in MySQL and I am running into a little problem. 我正在计算MySQL用户的年龄,但遇到了一个小问题。 I am able to successfully calculate the age of each user, however, when I try to count the number of users who are part of each age group, that is when I run into trouble. 我能够成功计算每个用户的年龄,但是,当我尝试计算每个年龄组中的用户数时,也就是遇到麻烦时。 Here is my query: 这是我的查询:

  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

I feel like I am close, it just is not working for me. 我觉得我很亲密,只是对我不起作用。 How would I count the number of users in each age group? 我如何计算每个年龄段的用户数量?

You need a subquery to access calculated column aliased Age in Group By clause 您需要一个子查询来访问Group By子句中别名为Age的计算列

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM