[LeetCode] Reformat Department Table

아르당·2026년 4월 7일

LeetCode

목록 보기
247/303
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

Table: Department

Column NameType
idint
revenueint
monthvarchar

SQL에서, (id, month)는 이 테이블에서 기본 키이다.
테이블은 각 부서의 월 수익에 대한 정보를 가지고 있다.
month는 ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]의 값을 가지고 있다.

department id 컬럼과 각 월 수익 컬럼이 있는 형태로 변경해라.

Example

Input:
Department table:

idrevenuemonth
18000Jan
29000Jan
310000Feb
17000Feb
16000Mar

Output:

idJan_RevenueFeb_RevenueMar_revenue...Dec_revenue
1800070006000...null
29000nullnull...null
3null10000null...null

Explanation: Apr부터 Dec까지 수익은 null이다.

Solved

-- Write your PostgreSQL query statement below
select id, 
	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
order by id
profile
내 마음대로 코드 작성하는 세상

0개의 댓글