好题分享、心路历程(力扣1179)—— case when

前阵子想开个专栏,叫【hard 题分享】。

既然今天发现了好题,心血来潮,就叫【好题分享】吧。

不过仅分享思路,原因竟然是博主懒得 code 了。。。

【题目介绍】

该题为力扣1179题,名为重新格式化部门表,非常符合该题的考查点。

【题型分类】

属于 case when 专题。

官网标为简单题,个人认为难度介于简单题与中等题之间~

【思路分享】

方法一:case when

该方法往往处理东西比较灵活、高级。

作为好题分享的原因,竟然是因为原表不是整理好的 id 列。。。(并非仅有1、2、3,而是重复不规整)

这也就意味着,单纯的行转列后,当存在重复的 id 时,某月的收入数据落在不同行的记录上,比如:

select id,
    case when month='Jan' then revenue end as Jan_Revenue,
    case when month='Feb' then revenue end as Feb_Revenue,
    case when month='Mar' then revenue end as Mar_Revenue
from Department

那么我们要做的处理,就是将它贴上去,或者整合起来。

虽然有点尴尬,这里采用聚合、求和整合,就搞定啦~

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
from Department
group by id

方法二:过滤、self join、left join

该方法写起来较繁杂,但思路清晰就 ok~

关键点1:过滤

# 分别过滤各月份至tmp1,...,tmp12
with tmp1 as
(select id,revenue as Jan_Revenue
from Department
where month='Jan')

关键点2:self join 横向拼接

# 分步连接各月份至tmp12,...,tmp123456789101112
self joinwith tmp12 as
(select tmp1.id,Jan_Revenue,Feb_Revenue
from tmp1,tmp2
where tmp1.id=tmp2.id)

关键点3:left join 获得全集

# 预处理
with tmp0 as
(select distinct id
from Department)
# 左连接获得全集
select tmp0.id,Jan_Revenue,...,Dec_Revenue
from tmp0 left join tmp123456789101112
on tmp0.id=tmp123456789101112.id

-END

https://leetcode.cn/problems/reformat-department-table/

posted @ 2022-12-16 17:27  找回那所有、  阅读(51)  评论(0)    收藏  举报
这里到底了哦~(●'◡'●)