1. 程式人生 > 其它 >SQL之行列轉換

SQL之行列轉換

技術標籤:資料庫面試必備sql資料庫

部門表 Department:

±--------------±--------+
| Column Name | Type |
±--------------±--------+
| id | int |
| revenue | int |
| month | varchar |
±--------------±--------+
(id, month) 是表的聯合主鍵。
這個表格有關於每個部門每月收入的資訊。
月份(month)可以取下列值 [“Jan”,“Feb”,“Mar”,“Apr”,“May”,“Jun”,“Jul”,“Aug”,“Sep”,"

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/reformat-department-table

編寫一個 SQL 查詢來重新格式化表,使得新的表中有一個部門 id 列和一些對應 每個月 的收入(revenue)列。
查詢得到的結果表:
±-----±------------±------------±------------±----±------------+
| 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個月份的收入列)。

select id,
sum(case month when "Jan" then revenue) as Jan_Revenue
sum(case month when "Feb" then revenue) as Feb_Revenue
from Department
group by id