[MYSQL Quick Start] case function

case function:

is a multi-branch function that returns one of several possible result expressions based on the value of a list of conditions.

Simple case function:

case 测试表达式
when 简单表达式1 then 结果表达式1
when 简单表达式2 then 结果表达式2..
when 简单表达式3 then 结果表达式n
[else 结果表达式n+1]

Example: Query the class number, class name, department number and class teacher number of students in the class table, and process the department number as follows:

When the serial number is 1, it displays "Computer Department"; when the serial number is 2, it displays "Software Engineering Department"; when the system number is 3, it displays "Internet of Things Department"

select 班号,班名 case 系号
when 1 then ‘软件工程系’
when 2 then '计算机系'
when 3 then '物联网系'
end as 系号,班主任号
from 班级表

Search case function:

case
when 布尔表达式1 then 结果表达式1
when 布尔表达式2 then 结果表达式2...
when 布尔表达式3 then 结构表达式n
[else 结果表达式n+1]
end

Example: Query 101 results and display it as a grade 

select 学号,课程号,
case
when 成绩>=90 then‘优’
when 成绩 between 80 and 90 then'良'
when 成绩 between 70 and 79 then'中'
when 成绩 between 60 and 69 then'及格'
when 成绩<60 then'不及格'
end 成绩
from 成绩表
where 课程号='101';

 Example: Count the number of boys and girls in each class. The header of the statistical results is: class number, number of boys, number of girls

select 班号,
count(case when 性别='男' then '男' end)男生数
count(case when 性别='女' then'女' end)女生数
from 学生表 group by 班号;

 Example: To judge the grade of achievement, and count the number of people at each grade.

select 
case 
when grade between 85 and 100 then '优'
when grade between 70 and 84 then'良'
when grade between 60 and 69 then'及格'
else '不及格'
end 等级,count(*)人数
from tb
group by  等级;

 

select case when age<25 or age is null then '25岁以下'
            when age>=25 then '25岁及以上'
            end age_cut,count(*)number
            from user_profile
            group by age_cut
            

 

select device_id,gender,
case 
when age>=25 then '25岁及以上'
when age>=20 then '20-24岁'
when age<20 then '20岁以下'
else '其他'
end as age_cut
from user_profile

 

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/124202656