๐Ÿ“Œ[SQL ๋ฌธ์ œ ํ’€์ด] leetcode - 1179. Reformat Department Table

๋ชจ๊น…ยท2023๋…„ 11์›” 9์ผ
0

๐Ÿ’ป ๋ฌธ์ œ

โœ๏ธ ์ •๋‹ต

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
;

๐Ÿ•ถ๏ธ ํ•ด์„ค

[ Group by - ์ „ ]

์ฝ”๋“œ

SELECT id
, CASE WHEN month='Jan' THEN revenue ELSE NULL END AS Jan_Revenue
, CASE WHEN month='Feb' THEN revenue ELSE NULL END AS Feb_Revenue
, CASE WHEN month='Mar' THEN revenue ELSE NULL END AS Mar_Revenue
FROM department
๊ฒฐ๊ณผ

idJan_RevenueFeb_RevenueMar_Revenue
18000nullnull
29000nullnull
3null10000null
1null7000null
1nullnull6000

[ Group by - ํ›„ ]

์ฝ”๋“œ

SELECT id
, CASE WHEN month='Jan' THEN revenue ELSE NULL END AS Jan_Revenue
, CASE WHEN month='Feb' THEN revenue ELSE NULL END AS Feb_Revenue
, CASE WHEN month='Mar' THEN revenue ELSE NULL END AS Mar_Revenue
FROM department
GROUP BY id;
๊ฒฐ๊ณผ

id : 1 - Jan_Revenue ๊ฒฝ์šฐ
(8000, null, null) ๊ฐ’์ด ๊ทธ๋ฃนํ™” ๋˜๋Š”๋ฐ ๋งจ ์•ž์— ์žˆ๋Š” 8000๋งŒ ํ™”๋ฉด์— ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค. ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ
id : 1 - Feb_Revenue ๊ฒฝ์šฐ
( null, 7000, null) ๊ฐ’์ด ๊ทธ๋ฃนํ™” ๋˜๋ฉด์„œ ๋งจ ์•ž์— null ๋งŒ ํ™”๋ฉด์— ํ‘œ์‹œ๋˜๋Š” ๊ฑฐ๋ผ๊ณ  ๋ณผ ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”.

idJan_RevenueFeb_RevenueMar_Revenue
18000nullnull
29000nullnull
3null10000null

์ด๋Ÿฐ ์‹์œผ๋กœ ๊ฐ’์ด ๋‚˜์˜ค๊ธฐ ๋•Œ๋ฌธ์— ์ง‘๊ณ„ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์‹ค์ œ ์กด์žฌํ•˜๋Š” ๊ฐ’์„ ์กฐ์ •ํ•ด ์ฃผ๋Š” ๋“ฏ ํ•˜๋„ค์š”.

profile
๋ฉˆ์ถ”์ง€ ์•Š๊ธฐ

0๊ฐœ์˜ ๋Œ“๊ธ€