

对一个字段进行分类处理我们就可以使用case when函数:
select case when age>=25 then '25岁及以上'
else '25岁以下' end as cn,
count(1) from user_profile
group by
case when age>=25 then '25岁及以上'
else '25岁以下' end
使用case when的时候会涉及一对一和一对多关系,也就是when的对象是否只有只一个
当你在统计人数的时候,如果只有一个,你可以group by age
但是当多个的时候,grouo by后面必须是整个case when
在mysql中,group by 和 order by 是可以使用select 当中的别名的(并不是严格按照sql执行顺序)
select case when age>=25 then '25岁及以上'
else '25岁以下' end as cn,
count(1) from user_profile
group by cn
但是在oracle和hive sql中,需要严格遵守顺序规则

2744

被折叠的 条评论
为什么被折叠?



