SQL 문제풀이

leetcode - 618. Students Report By Geography

Jerrytwo 2022. 8. 29. 20:18

난이도 : Hard

 

Table: Student

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| name        | varchar |
| continent   | varchar |
+-------------+---------+
There is no primary key for this table. It may contain duplicate rows.
Each row of this table indicates the name of a student and the continent they came from.

 

A school has students from Asia, Europe, and America.

Write an SQL query to pivot the continent column in the Student table so that each name is sorted alphabetically and displayed underneath its corresponding continent. The output headers should be America, Asia, and Europe, respectively.

The test cases are generated so that the student number from America is not less than either Asia or Europe.

The query result format is in the following example.

 

Example 1:

Input: 
Student table:
+--------+-----------+
| name   | continent |
+--------+-----------+
| Jane   | America   |
| Pascal | Europe    |
| Xi     | Asia      |
| Jack   | America   |
+--------+-----------+
Output: 
+---------+------+--------+
| America | Asia | Europe |
+---------+------+--------+
| Jack    | Xi   | Pascal |
| Jane    | null | null   |
+---------+------+--------+

 

 

SELECT MAX(CASE WHEN continent = 'America' THEN name END) America
     , MAX(CASE WHEN continent = 'Asia' THEN name END) Asia
     , MAX(CASE WHEN continent = 'Europe' THEN name END) Europe  
FROM (SELECT *
           , ROW_NUMBER() OVER (PARTITION BY continent ORDER BY name) row_id 
      FROM student) AS t
GROUP BY row_id

Accepted (75.21%)