条件判断函数

IF(expr , v1 , v2)

expr为真,返回v1,否则返回v2。

可以用as直接命名列名。

牛客题目:user_profile

id device_id gender age university gpa
1 2138 male 21 北京大学 3.4
2 3214 male 复旦大学 4
3 6543 female 20 北京大学 3.2
4 2315 female 23 浙江大学 3.6
5 5432 male 25 山东大学 3.8
6 2131 male 28 山东大学 3.3
7 4321 male 26 复旦大学 3.6

现在运营想要将用户划分为25岁以下和25岁及以上两个年龄段,分别查看这两个年龄段用户数量

本题注意:age为null 也记为 25岁以下

题解:

1
2
3
4
5
6
7
select
if (age >= 25, '25岁及以上', '25岁以下') as age_cut,
count(*)
from
user_profile
group by
age_cut;

结果(本博客所有结果的图片只对格式做出说明,不保证其数据完全相同。):

image-20230424172814193

Case

大于两种的分类。

牛客题目:user_profile

id device_id gender age university gpa
1 2138 male 21 北京大学 3.4
2 3214 male 复旦大学 4
3 6543 female 20 北京大学 3.2
4 2315 female 23 浙江大学 3.6

现在运营想要将用户划分为20岁以下,20-24岁,25岁及以上三个年龄段,分别查看不同年龄段用户的明细情况,请取出相应数据。(注:若年龄为空请返回其他。)

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
select
device_id,
gender,
(
case
when age < 20 then "20岁以下"
when age >= 20 and age <= 24 then "20-24岁"
when age >= 25 then "25岁及以上"
else "其他"
end
)as age_cut
from
user_profile;

这里注意的地方是(case ...)case在括号中,以及最后的else "其他" end结束符。

运行结果:

image-20230424172603368