计算25岁以上和以下的用户数量
题目:现在运营想要将用户划分为25岁以下和25岁及以上两个年龄段,分别查看这两个年龄段用户数量
本题注意:age为null 也记为 25岁以下
select '25岁以下',count(*)
from user_profile
where age < 25 or age is null
union all
select '25岁及以上',count(*)
from user_profile
where age >= 25;
——这个是运行成功的,但是没有用到条件函数
select case when age < 25 or age is null then "25岁以下"
when age >= 25 then "25岁及以上"
end as age_cut,
count(*) number
from user_profile
group by age_cut;
——这是用的mysql的写法,也成功了
我想尝试用Oracle的写法,但是怎么尝试都不成功,有没有办法能用Oracle的语法实现成功?
select age_cut,
count(age_cut) number
from (select case when age < 25 or age is null then '25岁以下'
when age >= 25 then '25岁及以上'
end age_cut
from user_profile)
group by age_cut;
我上面的这个写法,一直提示我非单组分组函数,括号from()里面的是运行成功了,但是外面的就一直是报错的,我想要的结果就是
输出:
25岁以下|4
25岁及以上|3
select age_cut
,count(*) num
from (select (case when age>=25 then '25岁及以上' else '25岁以下' end) age_cut
from user_profile)
group by age_cut;
--已帮你用oracle验证过,该语句可执行
没有装Oracle无法测试,不过感觉你语法没什么问题,应该是没有给到表别名,括号后面随便加个别名:
select age_cut,
count(age_cut) number
from (select case when age < 25 or age is null then '25岁以下'
when age >= 25 then '25岁及以上'
end age_cut
from user_profile)t
group by age_cut;
若有帮助,请采纳
同上,应该是子查询没有表别名
group by 后面把select的非聚合函数的字段或表达式放进去就行了,你这里是select的case when,那么group by后面也要有同样的case when
select case when age < 25 or age is null
then "25岁以下"
when age >= 25 then "25岁及以上"
end as age_cut,
count(*) number
from user_profile
group by case when age < 25 or age is null
then "25岁以下"
when age >= 25 then "25岁及以上"
end;