forked from siqichen-usc/LeetCode-SQL-Summary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
618_Students_Report_By_Geography.sql
31 lines (26 loc) · 1.17 KB
/
618_Students_Report_By_Geography.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
-- Solution 1: Window Function, Subquery, PIVOT/UNPIVOT
WITH tb1 AS (
-- Numbering student from each continent separately by their name alphabetically
SELECT *, ROW_NUMBER() OVER (PARTITION BY continent ORDER BY name) AS r
FROM student
)
-- each row will be a group of student name of whom from different continent and have same numbering
SELECT [America],[Asia],[Europe]
FROM tb1
PIVOT (
MIN(name) FOR continent IN ([America],[Asia],[Europe])
) pvt;
-- Solution 2: Window Function, Subquery, IFF
WITH tb1 AS (
-- Numbering student from each continent separately by their name alphabetically
SELECT ROW_NUMBER() OVER (PARTITION BY continent ORDER BY name) AS r,
IIF(continent = 'America', name, NULL) AS America,
IIF(continent = 'Asia', name, NULL) AS Asia,
IIF(continent = 'Europe', name, NULL) AS Europe
FROM student
)
-- Since numbering is unique in each continent,
-- in each numbering group (1-3 rows), there ia only one cell contained student name in each column (e.g. America, Asia, Europe)
SELECT MIN(America) AS America, MIN(Asia) AS Asia, MIN(Europe) AS Europe
FROM tb1
GROUP BY r;