题目:计算25岁以上和以下的用户数量
示例:user_profile
id | device_id | gender | age | university | gpa | active_days_within_30 | question_cnt | answer_cnt |
1 | 2138 | male | 21 | 北京大学 | 3.4 | 7 | 2 | 12 |
2 | 3214 | male | 复旦大学 | 4 | 15 | 5 | 25 | |
3 | 6543 | female | 20 | 北京大学 | 3.2 | 12 | 3 | 30 |
4 | 2315 | female | 23 | 浙江大学 | 3.6 | 5 | 1 | 2 |
5 | 5432 | male | 25 | 山东大学 | 3.8 | 20 | 15 | 70 |
6 | 2131 | male | 28 | 山东大学 | 3.3 | 15 | 7 | 13 |
7 | 4321 | male | 26 | 复旦大学 | 3.6 | 9 | 6 | 52 |
难点,这个25岁以上,以下 这个字段的value是怎么设置的?
错误1:
select
age as age_cut='25岁以上' ,count(device_id) as number
from user_profile
where age<25 or age is null
union all
select
age as age_cut='25岁及以上',count(device_id)as number
from user_profile
where age>=25;
怎么设置一个新的values?
select
'25岁以下' as avg_cut , count(device_id) as number
from user_profile
where age<25 or age is null
union all
select
'25岁及以上' as avg_cut, count(device_id)as number
from user_profile
where age>=25;
第二种解答:case when 完成筛选,对每行设计标签,然后group by进行筛选
select
case when age <25 or age is null then '25岁以下'
when age >= 25 then '25岁及以上'
end age_cnt,
count(device_id) as number
from
user_profile
group by
age_cnt;
表达式"age_cnt"被用作CASE语句的结果的别名。
CASE语句用于在SQL查询中创建条件逻辑。它根据"age"列的值进行评估,并根据条件为每行分配相应的标签。在这个语句中,"age_cnt"是根据"age"的值分类的结果的别名。
### 方法3
### 使用
if
(条件,输出情况
1
,输出情况
2
) 完成数据的判断
select
if
(age >=
25
,
'25岁及以上'
,
'25岁以下'
) as age_cut,
count(device_id) as number
from
user_profile
group by
age_cut
;