题目描述

(通过次数44,732 | 提交次数69,262,通过率64.58%)

部门表Department:
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| revenue       | int     |
| month         | varchar |
+---------------+---------+
(id, month) 是表的联合主键。
这个表格有关于每个部门每月收入的信息。
月份(month)可以取下列值 ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]。

编写一个 SQL 查询来重新格式化表,使得新的表中有一个部门 id 列和一些对应每个月 的收入(revenue)列。
查询结果格式如下面的示例所示:
Department 表:
+------+---------+-------+
| id   | revenue | month |
+------+---------+-------+
| 1    | 8000    | Jan   |
| 2    | 9000    | Jan   |
| 3    | 10000   | Feb   |
| 1    | 7000    | Feb   |
| 1    | 6000    | Mar   |
+------+---------+-------+
查询得到的结果表:
+------+-------------+-------------+-------------+-----+-------------+
| id   | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
+------+-------------+-------------+-------------+-----+-------------+
| 1    | 8000        | 7000        | 6000        | ... | null        |
| 2    | 9000        | null        | null        | ... | null        |
| 3    | null        | 10000       | null        | ... | null        |
+------+-------------+-------------+-------------+-----+-------------+
注意,结果表有 13 列 (1个部门 id 列 + 12个月份的收入列)。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reformat-department-table
//测试数据
Create table If Not Exists Department (id int, revenue int, month varchar(5));

insert into Department (id, revenue, month) values ('1', '8000', 'Jan');
insert into Department (id, revenue, month) values ('2', '9000', 'Jan');
insert into Department (id, revenue, month) values ('3', '10000', 'Feb');
insert into Department (id, revenue, month) values ('1', '7000', 'Feb');
insert into Department (id, revenue, month) values ('1', '6000', 'Mar');

解题思路

Department表保存了部门每个月的收入。一个部门一个月份一行记录。

题目要求:将表中数据转换成一个部门一行记录,不同月份使用不同的列来存储。

这是一个典型的行转列操作。Department表主键为(id, month),目标结果的主键为(id),数据粒度不一样,所以可以使用GROUP BY进行分组汇总。

针对目标结果的每个月份列,可以对源表数据进行CASE WHEN的条件筛选,不同的月份,使用对应月份的条件,最后再对结果取MAX即可。

参考SQL

未特别说明的情况下,参考SQL为基于MySQL8.0实现。
select
    id,
    max(case when month = 'Jan' then revenue end) Jan_Revenue,
    max(case when month = 'Feb' then revenue end) Feb_Revenue,
    max(case when month = 'Mar' then revenue end) Mar_Revenue,
    max(case when month = 'Apr' then revenue end) Apr_Revenue,
    max(case when month = 'May' then revenue end) May_Revenue,
    max(case when month = 'Jun' then revenue end) Jun_Revenue,
    max(case when month = 'Jul' then revenue end) Jul_Revenue,
    max(case when month = 'Aug' then revenue end) Aug_Revenue,
    max(case when month = 'Sep' then revenue end) Sep_Revenue,
    max(case when month = 'Oct' then revenue end) Oct_Revenue,
    max(case when month = 'Nov' then revenue end) Nov_Revenue,
    max(case when month = 'Dec' then revenue end) Dec_Revenue
from Department
group by id;
picture loss