You have a Student table containing student names and their continents. Write a SQL solution to pivot the continent column so that each name is sorted alphabetically and displayed underneath its corresponding continent.
Requirements:
- Output headers should be
America,Asia, andEurope - Names should be sorted alphabetically within each continent
- The test cases guarantee that America has at least as many students as Asia or Europe
Table Schema
| Column Name | Type | Description |
|---|---|---|
name
|
varchar | Student name |
continent
|
varchar | Continent (America, Asia, or Europe) |
Input & Output
| name | continent |
|---|---|
| Jane | America |
| Pascal | Europe |
| Xi | Asia |
| Jack | America |
| America | Asia | Europe |
|---|---|---|
| Jack | Xi | Pascal |
| Jane |
Students are grouped by continent and sorted alphabetically within each group. Since America has 2 students (Jack, Jane) and Asia/Europe each have 1, the second row shows null for Asia and Europe.
| name | continent |
|---|---|
| Alice | America |
| Bob | Asia |
| Charlie | Europe |
| America | Asia | Europe |
|---|---|---|
| Alice | Bob | Charlie |
When each continent has exactly one student, all students appear in the first row, sorted alphabetically within their respective continents.
| name | continent |
|---|---|
| John | America |
| John | America |
| Mary | Asia |
| America | Asia | Europe |
|---|---|---|
| John | Mary | |
| John |
Duplicate names are handled by the ROW_NUMBER() function, which assigns different ranks to duplicate entries, allowing both 'John' entries to appear in separate rows.
Constraints
-
nameandcontinentare varchar fields - The table may contain duplicate rows
-
Students come from exactly three continents:
America,Asia, andEurope - The number of students from America is not less than either Asia or Europe