我试图通过计算他们的生日来获得每个人的年龄。现在我需要将它们分组,我已经实现了。现在我想要的是计算20组及以下的数量,依此类推等等。
这是我的查询
select case when datediff(now(), birthday) / 365.25 > 50 then '51 & over' when datediff(now(), birthday) / 365.25 > 30 then '31 - 50' when datediff(now(), birthday) / 365.25 > 19 then '20 - 30' else 'under 20' end as age_group from members
结果是
我试图通过下面的查询对其进行分组
select case when datediff(now(), birthday) / 365.25 > 50 then '51 & over' when datediff(now(), birthday) / 365.25 > 30 then '31 - 50' when datediff(now(), birthday) / 365.25 > 19 then '20 - 30' else 'under 20' end as age_group from members group by age_group
** NOte:照片编辑。
我如何实现我需要将计数结果放在图表中。
答案 0 :(得分:1)
将查询换行类似于:
Select age_group, count(*)
From (
// your original query here
) t
Group by age_group
答案 1 :(得分:0)
只需在上次查询中添加一个计数(*):
select case when datediff(now(), birthday) / 365.25 > 50 then '51 & over' when datediff(now(), birthday) / 365.25 > 30 then '31 - 50' when datediff(now(), birthday) / 365.25 > 19 then '20 - 30' else 'under 20' end as age_group, count(*) from members group by age_group
答案 2 :(得分:0)
SELECT
concat(
datediff(now(), birthday)/365.25 div 20 * 20 + 1,
'-',
(datediff(now(), birthday)/365.25 div 20 + 1) * 20) AS age,
count(*)
FROM members
GROUP BY datediff(now(), birthday)/365.25 DIV 20
此查询将以以下格式提供结果
+-------+----------+
| age | count(*) |
+-------+----------+
| 1-20 | 2 |
| 21-40 | 1 |
| 41-60 | 1 |
+-------+----------+
基于以下表格定义和样本数据:
CREATE TABLE `stack` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`birthdate` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
insert into members values (null,'1973-10-02');
insert into members values (null,'1977-04-07');
insert into members values (null,'2006-07-03');
insert into members values (null,'2011-10-11');