File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Time: O(nlogn)
2+ # Space: O(n)
3+
4+ # Mary is a teacher in a middle school and she has a table seat storing
5+ # students' names and their corresponding seat ids.
6+ #
7+ # The column id is continuous increment.
8+ # Mary wants to change seats for the adjacent students.
9+ # Can you write a SQL query to output the result for Mary?
10+ # +---------+---------+
11+ # | id | student |
12+ # +---------+---------+
13+ # | 1 | Abbot |
14+ # | 2 | Doris |
15+ # | 3 | Emerson |
16+ # | 4 | Green |
17+ # | 5 | Jeames |
18+ # +---------+---------+
19+ #
20+ # For the sample input, the output is:
21+ # +---------+---------+
22+ # | id | student |
23+ # +---------+---------+
24+ # | 1 | Doris |
25+ # | 2 | Abbot |
26+ # | 3 | Green |
27+ # | 4 | Emerson |
28+ # | 5 | Jeames |
29+ # +---------+---------+
30+ #
31+ # Note:
32+ # If the number of students is odd, there is no need to change the last one's seat.
33+
34+ SELECT
35+ s1 .id , COALESCE(s2 .student , s1 .student ) AS student
36+ FROM
37+ seat s1
38+ LEFT JOIN
39+ seat s2 ON ((s1 .id + 1 ) ^ 1 ) - 1 = s2 .id
40+ ORDER BY s1 .id ;
You can’t perform that action at this time.
0 commit comments