627.交换工资
题目
代码
update salary
set sex=
(
case sex
when 'f' then 'm'
when 'm' then 'f'
end
);
知识点
update语句
update <table_name>
set <column1> = <value1>,<column2> = <value2>...
case表达式
case
when <condition> then <expression>
when <condition> then <expression>
...
eles<expression>
end
- 将表内某列特定值替换为其他值时,用case表达式,如下使用
case column
when <condition> then <expression>
when <condition> then <expression>
...
eles<expression>
end
【注意】 使用update更新数据表前,要将原表备份。
620.有趣的电影
题目
代码
select *
from cinema
where description <> 'boring'
and id%2=1
order by rating desc
知识点
判断奇数
- 直接计算,number % 2 = 1
- 使用mod()函数,即mod(num,2)=1
181.超过经理收入的员工
题目
代码
select e.Name as Employee
from Employee e
join Employee m
on e.ManagerId = m.Id
where e.Salary > m.Salary
知识点
自连接
把一张表当作两张表进行连接操作。
1179.重新格式化部门表
题目
代码
select id,
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
from Department
group by id;
知识点
行转列后使用max()或sum()
case表达式
可以利用case表达式来添加新列。
case column
when <condition> then <expression>
eles<expression>
end new_column
单引号(’)和反勾号(`)的区别
- 单引号是标记字符串。
- 反勾号是标记数据库、表名、索引名称、列名和别名。
178.分数排名
题目
代码
方法1(窗口函数)
select Score,
dense_rank() over (order by Score desc) as 'Rank'
from Scores;
方法2(统计方法排序)
select a.Score as Score,
(select count(distinct b.Score)
from Scores b
where b.Score >= a.Score) as Rank
from Scores a
order by a.Score desc
知识点
窗口函数(OLAP函数)
窗口函数主要用于在每组内进行排名(不减少原表的行数),兼具分组和排序的功能。
【注意】窗口函数是对where或group by子句处理后的结果进行操作,原则上智能写在select子句中。
窗口函数基本语法如下:
<窗口函数> over (partition by <分组列名>
order by <排序列名>)
partition by 可以省略。
类别
- 专用窗口函数,用于排名的函数有:
- rank():可以输出并列分数的相同名次,会占用下一个名次的位置,名次不连续。
- dense_rank():输出并列分数的相同名次,不会占用下一个名次位置,名次是连续的。
- row_number():并列分数名次不同,名次连续。
三者区别实例如下:
【注意】上面三个专用窗口函数后面的括号不要任何参数。
- 聚合函数,如:
- sum()
- avg()
- count()
【注意】聚合函数后面的括号要指定聚合的列名
统计方法排序
select count(distinct b.Score) from Scores b where b.Score >= X as Rank;
该方法就是选出大于等于X的所有分数的个数(去掉重复的分数),例如:只有2个数大于等于X,则X的排名为2。