题解 | 计算25岁以上和以下的用户数量
计算25岁以上和以下的用户数量
https://www.nowcoder.com/practice/30f9f470390a4a8a8dd3b8e1f8c7a9fa
select case when age < 25 or age is null then '25岁以下' when age >= 25 then '25岁及以上' end as age_cut, count(*) as number from user_profile group by age_cut
如果去掉 GROUP BY age_cut
:
- 查询会报错(因为使用了聚合函数 COUNT(*) 但没有指定分组)
- 或者(在某些SQL方言中)会返回所有记录和总记录数,而不是按年龄段的分类统计
GROUP BY age_cut
是这种分类统计查询的必要部分,它:
- 确保数据按年龄段正确分组
- 使 COUNT(*) 能够分别计算每个年龄段的记录数
- 是SQL聚合查询的标准用法