SQL-leetcode—1179. 重新格式化部門表

1179. 重新格式化部門表

表 Department:

±--------------±--------+
| Column Name | Type |
±--------------±--------+
| id | int |
| revenue | int |
| month | varchar |
±--------------±--------+
在 SQL 中,(id, month) 是表的聯合主鍵。
這個表格有關于每個部門每月收入的信息。
月份(month)可以取下列值 [“Jan”,“Feb”,“Mar”,“Apr”,“May”,“Jun”,“Jul”,“Aug”,“Sep”,“Oct”,“Nov”,“Dec”]。

重新格式化表格,使得 每個月 都有一個部門 id 列和一個收入列。

以 任意順序 返回結果表。

結果格式如以下示例所示。

示例 1:

輸入:
Department table:
±-----±--------±------+
| 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 列用于各個月份)。

題解

格式化表格,使得 每個月 都有一個部門 id 列和一個收入列

  • 經典的行轉列,可以使用聚合函數+group by + case when來實現

方法一 SUM + group by

selectid,SUM(case when month='Jan' then revenue else null end) as Jan_Revenue,SUM(case when month='Feb' then revenue else null end) as Feb_Revenue,SUM(case when month='Mar' then revenue else null end) as Mar_Revenue,SUM(case when month='Apr' then revenue else null end) as Apr_Revenue,SUM(case when month='May' then revenue else null end) as May_Revenue,SUM(case when month='Jun' then revenue else null end) as Jun_Revenue,SUM(case when month='Jul' then revenue else null end) as Jul_Revenue,SUM(case when month='Aug' then revenue else null end) as Aug_Revenue,SUM(case when month='Sep' then revenue else null end) as Sep_Revenue,SUM(case when month='Oct' then revenue else null end) as Oct_Revenue,SUM(case when month='Nov' then revenue else null end) as Nov_Revenue,SUM(case when month='Dec' then revenue else null end) as Dec_Revenue
from Department
group by id

方法二 MAX + group by

selectid,MAX(case when month='Jan' then revenue else null end) as Jan_Revenue,MAX(case when month='Feb' then revenue else null end) as Feb_Revenue,MAX(case when month='Mar' then revenue else null end) as Mar_Revenue,MAX(case when month='Apr' then revenue else null end) as Apr_Revenue,MAX(case when month='May' then revenue else null end) as May_Revenue,MAX(case when month='Jun' then revenue else null end) as Jun_Revenue,MAX(case when month='Jul' then revenue else null end) as Jul_Revenue,MAX(case when month='Aug' then revenue else null end) as Aug_Revenue,MAX(case when month='Sep' then revenue else null end) as Sep_Revenue,MAX(case when month='Oct' then revenue else null end) as Oct_Revenue,MAX(case when month='Nov' then revenue else null end) as Nov_Revenue,MAX(case when month='Dec' then revenue else null end) as Dec_Revenue
from Department
group by id

方法三 MIN + group by

selectid,MIN(case when month='Jan' then revenue else null end) as Jan_Revenue,MIN(case when month='Feb' then revenue else null end) as Feb_Revenue,MIN(case when month='Mar' then revenue else null end) as Mar_Revenue,MIN(case when month='Apr' then revenue else null end) as Apr_Revenue,MIN(case when month='May' then revenue else null end) as May_Revenue,MIN(case when month='Jun' then revenue else null end) as Jun_Revenue,MIN(case when month='Jul' then revenue else null end) as Jul_Revenue,MIN(case when month='Aug' then revenue else null end) as Aug_Revenue,MIN(case when month='Sep' then revenue else null end) as Sep_Revenue,MIN(case when month='Oct' then revenue else null end) as Oct_Revenue,MIN(case when month='Nov' then revenue else null end) as Nov_Revenue,MIN(case when month='Dec' then revenue else null end) as Dec_Revenue
from Department
group by id

可能一開始看到SUM、MAX、MIN會不理解為啥?

在這里插入圖片描述
在這里插入圖片描述

可以看下這2個圖例呢?

中間分組的過程其實是內部存儲的,無法查詢出來的一個虛擬的結果,一個框是一個集合的內容,這樣的話就比較好理解為啥用聚合函數了。

如果不使用聚合函數會怎么樣呢?
如果不使用的話,行數不會減少,會和輸入數據一樣的行數,就需要考慮一個合并的問題了。
大致效果是:
1, 100,null,null,null,…
2,null,100,null,null,…
1,null,100,null,null,…

顯然id=1的數據沒有合并,違背了行轉列的預期效果。

分析案例

解題思路
由于篩選結果中每個ID是一個記錄 因此GROUP BY ID.
每個月份是一列,因此篩選每個月份時使用CASE [when…then…] END只取當前月份.
需要使用SUM()聚合函數 因為如果沒有聚合函數 篩選出來的是
GROUP BY、CASE…END之后的第一行.

比如 Department 表:
+------+---------+-------+
| id   | revenue | month |
+------+---------+-------+
| 1    | 8000    | Jan   |
| 2    | 9000    | Jan   |
| 3    | 10000   | Feb   |
| 1    | 7000    | Feb   |
| 1    | 6000    | Mar   |
+------+---------+-------+GROUP BY ID
+------+---------+-------+
| id   | revenue | month |
+------+---------+-------+
| 1    | 8000    | Jan   |
| 1    | 7000    | Feb   |
| 1    | 6000    | Mar   |
-------------------------
| 2    | 9000    | Jan   |
-------------------------
| 3    | 10000   | Feb   |
+------+---------+-------+如果沒有聚合函數 只輸出第一行 比如
SELECT ID, (CASE WHEN MONTH='JAN' THEN REVENUE END) AS JAN_REVENUE, 
(CASE WHEN MONTH='FEB' THEN REVENUE END) AS FEB_REVENUE  
FROM DEPARTMENT GROUP BY ID
會輸出
+------+-------------+-------------+
| ID   | JAN_REVENUE | FEB_REVENUE |
+------+-------------+-------------+
| 1    | 8000        | NULL        |
| 2    | 7000        | NULL        |
| 3    | NULL        | 10000       |
+------+-------------+-------------+
其中 ID=1 的 FEB_REVENUE 結果不對,這是因為 ID=1 時, (CASE WHEN MONTH='FEB' THEN REVENUE END)= [NULL, 7000, NULL], 沒有聚合函數會只取第一個,即NULL

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/66921.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/66921.shtml
英文地址,請注明出處:http://en.pswp.cn/web/66921.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【Address Overfitting】解決過擬合的三種方法

目錄 1. 收集更多數據實踐方法:適用場景:優缺點: 2. 特征選擇方法介紹:實踐示例:適用場景:優缺點: 3. 正則化(Regularization)正則化類型:實踐示例&#xff1…

面向通感一體化的非均勻感知信號設計

文章目錄 1 非均勻信號設計的背景分析1.1 基于OFDM波形的感知信號1.2 非均勻信號設計的必要性和可行性1.2 非均勻信號設計的必要性和可行性 3 通感一體化系統中的非均勻信號設計方法3.1 非均勻信號的設計流程(1)均勻感知信號設計(2&#xff0…

【深度學習】搭建PyTorch神經網絡進行氣溫預測

第一步 數據加載與觀察 ①導包 import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.optim as optim import warnings warnings.filterwarnings("ignore") %matplotlib inline ②加載數據 features pd.read_csv(…

ESP8266 NodeMCU與WS2812燈帶:實現多種花樣變換

在現代電子創意項目中,LED燈帶的應用已經變得極為廣泛。通過結合ESP8266 NodeMCU的強大處理能力和FastLED庫的高效功能,我們可以輕松實現多達100種燈帶變換效果。本文將詳細介紹如何使用Arduino IDE編程,實現從基礎到高級的燈光效果&#xff…

pycharm踩坑(1)

由于我重裝系統,導致我的pycharm需要進行重裝,因此我覺得需要記錄一下,pycharm的正確使用方法 漢化 漢化很重要,除非你從小就雙語教學,不然你看著那些英文就是會消耗大量的精力 我使用的pycharm版本是pycharm-commun…

#HarmonyOS篇:build-profile.json5里面配置productsoh-package.json5里面dependencies依賴引入

oh-package.json5 用于描述包名、版本、入口文件和依賴項等信息。 {"license": "","devDependencies": {},"author": "","name": "entry","description": "Please describe the basic…

OpenCV2D 特征框架 (11)特征檢測與描述用于檢測二值圖像中連通區域(即“斑點”或“blob”)的類cv::SimpleBlobDetector的使用

操作系統:ubuntu22.04 OpenCV版本:OpenCV4.9 IDE:Visual Studio Code 編程語言:C11 算法描述 cv::SimpleBlobDetector 是 OpenCV 中用于檢測二值圖像中連通區域(即“斑點”或“blob”)的類。這些連通區域可以是白色前…

關于deepin上運行Qt開發的程序

國產化替代是將來各單位的主流趨勢,探索自行開發應用程序在國產操作系統上正常運行是將來的主要工作之一。本文淺嘗gui程序在統信社區版——deepin上遇到的小問題。 使用Qt在deepin上做了一個類似gif的幀動畫彈窗,在編譯運行時,程序可以正常…

Unity自學之旅05

Unity自學之旅05 Unity學習之旅⑤📝 AI基礎與敵人行為🥊 AI導航理論知識(基礎)開始實踐 🎃 敵人游戲機制追蹤玩家攻擊玩家子彈碰撞完善游戲失敗條件 🤗 總結歸納 Unity學習之旅⑤ 📝 AI基礎與敵…

我想通過python語言,學習數據結構和算法該如何入手?

學習數據結構和算法是編程中的重要基礎,Python 是一個非常適合入門的語言。以下是學習數據結構和算法的步驟和建議: 1. 掌握 Python 基礎 確保你對 Python 的基本語法、數據類型、控制結構(如循環、條件語句)、函數等有扎實的理…

淺談Unity中Canvas的三種渲染模式

Overview UGUI通過 Canvas 組件渲染和管理UI元素。Canvas 是 UI 元素的容器,它決定了 UI 元素的渲染方式以及它們在屏幕上的顯示效果。Canvas 有三種主要的渲染模式,每種模式有不同的用途和特點。本文將介紹這三種渲染模式 1. Screen Space - Overlay 模…

Unity中在UI上畫線

在UI中畫一條曲線 我封裝了一個組件,可以實現基本的畫線需求. 效果 按住鼠標左鍵隨手一畫. 用起來也很簡單,將組件掛到空物體上就行了,紅色的背景是Panel. 你可以將該組件理解為一個Image,只不過形狀更靈活一些罷了,所以它要放在下面的層級(不然可能會被擋住). 代碼 可以…

2024.1.22 安全周報

政策/標準/指南最新動態 01 工信部印發《關于加強互聯網數據中心客戶數據安全保護的通知》 原文: https://www.secrss.com/articles/74673 互聯網數據中心作為新一代信息基礎設施,承載著千行百業的海量客戶數據,是關系國民經濟命脈的重要戰略資源。…

探索 LLM:從基礎原理到 RAG 實現的深度解析

一.LLM基礎知識 1.1 大語言模型(Large Language Model,LLM) 他是模型,是 AI 能力的核心。他是語言模型,其核心能力在于語言能力。他是大語言模型,與傳統模型相比,它最大的特點就是“大”。 1…

Mac cursor設置jdk、Maven版本

基本配置 – Cursor 使用文檔 首先是系統用戶級別的設置參數,運行cursor,按下ctrlshiftp,輸入Open User Settings(JSON),在彈出的下拉菜單中選中下面這樣的: 在打開的json編輯器中追加下面的內容: {"…

ARM64平臺Flutter環境搭建

ARM64平臺Flutter環境搭建 Flutter簡介問題背景搭建步驟1. 安裝ARM64 Android Studio2. 安裝Oracle的JDK3. 安裝 Dart和 Flutter 開發插件4. 安裝 Android SDK5. 安裝 Flutter SDK6. 同意 Android 條款7. 運行 Flutter 示例項目8. 修正 aapt2 報錯9. 修正 CMake 報錯10. 修正 N…

selenium clear()方法清除文本框內容

在使用Selenium進行Web自動化測試時,清除文本框內容是一個常見的需求。這可以通過多種方式實現,取決于你使用的是哪種編程語言(如Python、Java等)以及你的具體需求。以下是一些常見的方法: 1. 使用clear()方法 clear…

基于海思soc的智能產品開發(視頻的后續開發)

【 聲明:版權所有,歡迎轉載,請勿用于商業用途。 聯系信箱:feixiaoxing 163.com】 前面我們討論了camera,也討論了屏幕驅動,這些都是基礎的部分。關鍵是,我們拿到了這些視頻數據之后,…

vue3+webOffice合集

1、webOffice 初始化 1)officeType: 文檔位置:https://solution.wps.cn/docs/web/quick-start.html#officetype 2)appId: 前端使用appId 后端需要用到AppSecret 3)fileId: 由后端返回,前端無法生成,與上傳文…

2025牛客寒假算法營2

A題 知識點&#xff1a;模擬 打卡。檢查給定的七個整數是否僅包含 1,2,3,5,6 即可。為了便于書寫&#xff0c;我們可以反過來&#xff0c;檢查這七個整數是否不為 4 和 7。 時間 O(1)&#xff1b;空間 O(1)。 #include <bits/stdc.h> using namespace std;signed main()…