본문 바로가기
Data Science/SQL

[SQL/오답] 데이터 피벗(Pivot): 세로로 흐르는 데이터를 가로로 펼치는 기술 (LeetCode1179 Easy)

by 에르모사 쩐뉴 2026. 2. 8.

[리트코드] |1179. Reformat Department Table; CASE WHEN

https://leetcode.com/problems/reformat-department-table/description/

1. Problem

부서별 월 매출이 여러 행(Row)으로 나열된 Long Format 데이터를, 각 월이 컬럼(Column)이 되는 Wide Format으로 재구성해야 한다.

  • 핵심 과제: 하나의 id에 대해 12개의 월 데이터를 한 줄로 압축하여 표현하는 '데이터 재구조화' 능력을 테스트한다.

2. Solution: SUM(CASE WHEN)을 이용한 수동 피벗

각 월에 해당하는 값만 추출하고, SUM 함수를 통해 그룹화된 id별로 데이터를 한 행에 모은다.

3. Takeaway: 왜 IN 서브쿼리는 정답이 될 수 없는가? (객관적 분석)

  • 데이터 타입의 불일치 (Boolean Trap): 유진 님의 오답인 revenue IN (SELECT ...)은 "매출액이 해당 월의 매출 목록에 포함되는가?"라는 질문에 대한 True(1) 또는 False(0) 값을 반환한다. 문제에서 요구한 것은 실제 '매출액(숫자)'이므로 비즈니스 로직에 맞지 않는다.
  • 그룹화(Aggregation)의 부재: GROUP BY id 없이 SELECT 문을 작성하면, 원본 테이블의 행 개수가 그대로 유지된다. 피벗의 목적은 여러 행을 단 하나의 요약된 행으로 합치는 것이므로 집계 함수(SUM, MAX 등)와 GROUP BY는 필수 짝꿍이다.
  • SUM의 역할: 여기서 SUM은 실제로 더하기를 수행한다기보다, CASE WHEN으로 걸러진 특정 월의 값(나머지 월은 NULL)을 한 행으로 끌어올리는(Flattening) 역할을 한다.

Table: Department

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| revenue     | int     |
| month       | varchar |
+-------------+---------+
In SQL,(id, month) is the primary key of this table.
The table has information about the revenue of each department per month.
The month has values in ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].
 

Reformat the table such that there is a department id column and a revenue column for each month.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Department table:
+------+---------+-------+
| id   | revenue | month |
+------+---------+-------+
| 1    | 8000    | Jan   |
| 2    | 9000    | Jan   |
| 3    | 10000   | Feb   |
| 1    | 7000    | Feb   |
| 1    | 6000    | Mar   |
+------+---------+-------+
Output: 
+------+-------------+-------------+-------------+-----+-------------+
| id   | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
+------+-------------+-------------+-------------+-----+-------------+
| 1    | 8000        | 7000        | 6000        | ... | null        |
| 2    | 9000        | null        | null        | ... | null        |
| 3    | null        | 10000       | null        | ... | null        |
+------+-------------+-------------+-------------+-----+-------------+
Explanation: The revenue from Apr to Dec is null.
Note that the result table has 13 columns (1 for the department id + 12 for the months).

 

1. 정답 코드

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,
    SUM(CASE WHEN month = 'Apr' THEN revenue END) AS Apr_Revenue,
    SUM(CASE WHEN month = 'May' THEN revenue END) AS May_Revenue,
    SUM(CASE WHEN month = 'Jun' THEN revenue END) AS Jun_Revenue,
    SUM(CASE WHEN month = 'Jul' THEN revenue END) AS Jul_Revenue,
    SUM(CASE WHEN month = 'Aug' THEN revenue END) AS Aug_Revenue,
    SUM(CASE WHEN month = 'Sep' THEN revenue END) AS Sep_Revenue,
    SUM(CASE WHEN month = 'Oct' THEN revenue END) AS Oct_Revenue,
    SUM(CASE WHEN month = 'Nov' THEN revenue END) AS Nov_Revenue,
    SUM(CASE WHEN month = 'Dec' THEN revenue END) AS Dec_Revenue
FROM Department
GROUP BY id;

 

이 문제는 조건별 집계(pivot) 문제야.

SUM(CASE WHEN month = 'Jan' THEN revenue END) AS Jan_Revenue

 

  • CASE → 월별로 고르기
  • SUM → 한 행으로 압축
  • GROUP BY id → 부서별 한 줄

 

 

 

2. 오답 코드 

SELECT id, 
  revenue IN (SELECT revenue FROM Department WHERE month = 'Jan') AS Jan_Revenue,  #True/False 값을 반환
  revenue IN (SELECT revenue FROM Department WHERE month = 'Feb') AS Feb_Revenue,  #문제는 월별 revenue숫자를 원하지, boolean값을 원하지 않음
  revenue IN (SELECT revenue FROM Department WHERE month = 'Mar') AS Mar_Revenue,
  revenue IN (SELECT revenue FROM Department WHERE month = 'Apr') AS Apr_Revenue,
  revenue IN (SELECT revenue FROM Department WHERE month = 'May') AS May_Revenue,
  revenue IN (SELECT revenue FROM Department WHERE month = 'Jun') AS Jun_Revenue,
  revenue IN (SELECT revenue FROM Department WHERE month = 'Jul') AS Jul_Revenue,
  revenue IN (SELECT revenue FROM Department WHERE month = 'Aug') AS Aug_Revenue,
  revenue IN (SELECT revenue FROM Department WHERE month = 'Sep') AS Sep_Revenue,
  revenue IN (SELECT revenue FROM Department WHERE month = 'Oct') AS Oct_Revenue,
  revenue IN (SELECT revenue FROM Department WHERE month = 'Nov') AS Nov_Revenue,
  revenue IN (SELECT revenue FROM Department WHERE month = 'Dec') AS Dec_Revenue  
FROM Department; # id값으로 묶이지 않음