SQL系列文章目录
前言
SQL 05 case when、If等分支判断语句.
一、背景
来源:力扣 链接:https://leetcode-cn.com/problems/department-top-three-salaries/
表: Employee Id是该表的主键列。 departmentId是Department表中ID的外键。 该表的每一行都表示员工的ID、姓名和工资。它还包含了他们部门的ID。 表:department Id是该表的主键列。 该表的每一行表示部门ID和部门名。
二、创建“背景”的代码
create database test1;
create table department(
id int not null,
name varchar(15) not null,
primary key(id)
);
create table employee(
id int not null,
name varchar(15) not null,
salary int not null,
deparmentId int not null,
primary key(id),
foreign key(deparmentId) references department(id)
);
insert into department values( 1 ,'IT'),( 2 ,'Sales')
insert into employee values (1 ,'Joe' ,85000, 1),
(2,'Henry',80000,2),
(3 , 'Sam' ,60000 ,2 ),
(4 ,'Max' ,90000 ,1 ),
(5 , 'Janet' , 69000 , 1 ),
(6 , 'Randy' , 85000 ,1 ),
(7 ,' Will' , 70000 , 1 )
select *
from department
select *
from employee
三、解题
判断某值可能的情况<=2,不符合要求修改它
我们什么时候会用到判断分支语句呢?比如我们要对换表内所有性别,如果它是男,那么就设置为女,如果它是女,则设置为男。
If(sex='m','f','m')
IF( expr1 , expr2 , expr3 )
IFNULL( expr1 , expr2 )
IFNULL(name,'john')
判断某值的可能大于2,可用case when
SUM(CASE WHEN month='Jan' THEN revenue END) AS Jan_Revenue,
SUM(CASE WHEN month='Feb' THEN revenue END) AS Feb_Revenue,
SUM(CASE WHEN month='Mar' THEN revenue END) AS Mar_Revenue,
SUM(CASE WHEN month='Apr' THEN revenue END) AS Apr_Revenue,
SUM(CASE WHEN month='May' THEN revenue END) AS May_Revenue,
SUM(CASE WHEN month='Jun' THEN revenue END) AS Jun_Revenue,
SUM(CASE WHEN month='Jul' THEN revenue END) AS Jul_Revenue,
SUM(CASE WHEN month='Aug' THEN revenue END) AS Aug_Revenue,
SUM(CASE WHEN month='Sep' THEN revenue END) AS Sep_Revenue,
SUM(CASE WHEN month='Oct' THEN revenue END) AS Oct_Revenue,
SUM(CASE WHEN month='Nov' THEN revenue END) AS Nov_Revenue,
SUM(CASE WHEN month='Dec' THEN revenue END) AS Dec_Revenue
case when [字段]<判断符合>'字符串或真值' then [条件满足后,字段等于什么]
case when ……then
…………
end
总结
分支过多时,用case when;分支不多时,用 if。
|