部门表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');
selectid,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_Revenuefrom Departmentgroup by id;

笔试题合集免费领取方法
方法一:关注公众号【跟强哥学SQL】,回复关键字【力扣】获取链接。
方法二:访问【SQL网】:https://sql.wang/sql-leetcode/sql-exercise
文章转载自跟强哥学SQL,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




