240604 Today I Learn
Pivot Table
๐ก ํผ๋ฒ ํ ์ด๋ธ(pivot table)
ํ์ ํ๊ณผ ์ด์ ์ ํํ๋ ๋ฑ์ ๊ณผ์ ์ ํตํ์ฌ ํต๊ณ๋ฅผ ์ฌ์ ๋ ฌํ๊ณ , ๊ทธ ๊ฒฐ๊ณผ๋ก ํ ๋ฐ์ดํฐ๋ฅผ ์์ฝํ๋ ๋ฐฉ๋ฒ. ์ด์๋ ์ง๊ณํจ์(ํฉ๊ณ, ํ๊ท ๋ฑ)๊ฐ ์ฌ์ฉ๋ ์ ์๋ค.
SQL๋ก Unpivot ํ๊ธฐ
1. ์ผ๋ จ ๋ณํธ๋ฅผ ๊ฐ์ง ํ ์ด๋ธ ๋ง๋ค๊ธฐ
SELECT 1 AS idx
UNION ALL SELECT 2 AS idx
UNION ALL SELECT 3 AS idx
UNION ALL SELECT 4 AS idx
2. ํผ๋ฒ ํ ์ด๋ธ์ ๋ง๋ค๊ณ ์ด๋ฅผ CROSS JOIN ํ๊ธฐ
SELECT *
FROM quarterly_sales
CROSS JOIN (SELECT 1 AS idx
UNION ALL SELECT 2 AS idx
UNION ALL SELECT 3 AS idx
UNION ALL SELECT 4 AS idx)idxs
3. ํผ๋ฒ ํ ์ด๋ธ์ ๊ฒฐํฉํ๊ธฐ
SELECT q.year AS year,
CASE WHEN idxs.idx =1 THEN 'q1'
WHEN idxs.idx =2 THEN 'q2'
WHEN idxs.idx =3 THEN 'q3'
ELSE 'q4' END quarter,
CASE WHEN idxs.idx =1 THEN q.q1
WHEN idxs.idx =2 THEN q.q2
WHEN idxs.idx =3 THEN q.q3
ELSE q.q4 END sales
FROM quarterly_sales q
CROSS JOIN (SELECT 1 AS idx
UNION ALL SELECT 2 AS idx
UNION ALL SELECT 3 AS idx
UNION ALL SELECT 4 AS idx) idxs
๊ณผ์
Assume you're given two tables containing data about Facebook Pages and their respective likes (as in "Like a Facebook Page").
Write a query to return the IDs of the Facebook pages that have zero likes. The output should be sorted in ascending order based on the page IDs.
SELECT DISTINCT p.page_id
FROM pages p
LEFT JOIN page_likes l ON p.page_id = l.page_id
WHERE l.liked_date is NULL;
SELECT part, assembly_step
FROM parts_assembly
WHERE finish_date is NULL;
SELECT ROUND(COUNT(CASE WHEN call_category = 'n/a' or call_category is NULL THEN 1 ELSE NULL END)*100.0
/COUNT(*), 1) uncategorised_call_pct
FROM callers;
'๐ Today I Learn > ๐ My SQL' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
SQL Challenge ์ธ์ #6 ๋งค์ถ๋ถ์ (0) | 2024.06.07 |
---|---|
SQL Challenge ์ธ์ #4 ๋ฆฌํ ์ , ์ฝํธํธ ๋ถ์ (0) | 2024.05.30 |
SQL Challenge ์ธ์ #3 ํผ๋(Funnel)๋ถ์ (0) | 2024.05.29 |
SQL Challenge ์ธ์ #2 ์ด๋ํ๊ท ๊ณผ ๋น์จ (0) | 2024.05.27 |
SQL Challenge ์ธ์ #1 ์๋์ฐ ํจ์, WITH์ (0) | 2024.05.27 |