我已经绞尽脑汁待了两天。我需要计算每个年龄段的成员,但无法弄清楚如何。我已经做到这一点,但这仅显示了成员的年龄组,但不计算它们。
SELECT
CASE
WHEN YEAR(CURRENT_DATE()) - YEAR(birth_date) - (RIGHT(CURRENT_DATE(), 5) < RIGHT (birth_date, 5)) BETWEEN 12 AND 18 THEN '12-18'
WHEN YEAR(CURRENT_DATE()) - YEAR(birth_date) - (RIGHT(CURRENT_DATE(), 5) < RIGHT (birth_date, 5)) BETWEEN 19 AND 55 then '19-55'
ELSE '56 or older'
END AS age_group
FROM members
ORDER BY age_group
答案 0 :(得分:1)
您需要告诉查询执行计数。您还需要按要计算的字段进行分组。
试试这个:
select count(*) as the_count,
case
when YEAR(CURRENT_DATE()) - YEAR(birth_date) - (RIGHT(CURRENT_DATE(), 5) < RIGHT (birth_date, 5)) between 12 AND 18 THEN '12-18'
when YEAR(CURRENT_DATE()) - YEAR(birth_date) - (RIGHT(CURRENT_DATE(), 5) < RIGHT (birth_date, 5)) between 19 AND 55 then '19-55'
else '56 or older'
end
as age_group
from members group by age_group order by age_group;
点击以下链接查看正在运行的演示:
答案 1 :(得分:1)
您已经提取了所需的数据。要对其进行计数,请将其作为子查询嵌入,并通过group by子句计算每个组的结果。通过为子查询中的每个成员添加唯一标识符,它允许每个组中的成员计数在组中生存(即,不会折叠为每个组的单个行)。
SELECT age_group, COUNT(*) AS group_count
FROM
(SELECT
- - add a unique identifier for each member here as a select attribute,
CASE
WHEN YEAR(CURRENT_DATE()) - YEAR(birth_date) - (RIGHT(CURRENT_DATE(), 5) < RIGHT (birth_date, 5)) BETWEEN 12 AND 18 THEN '12-18'
WHEN YEAR(CURRENT_DATE()) - YEAR(birth_date) - (RIGHT(CURRENT_DATE(), 5) < RIGHT (birth_date, 5)) BETWEEN 19 AND 55 then '19-55' ELSE '56 or older' END AS age_group
FROM members) AS tab_age_groups
GROUP BY age_group
ORDER BY age_group;