MEDIUMSolve on LeetCode
626. Exchange Seats
Problem Statement
Swap the seat id of every two consecutive students. If the number of students is odd, the last student's id is not swapped. Return the result ordered by id in ascending order.
Table Schema
Table: Seat
+-------------+---------+
| id | int |
| student | varchar |
+-------------+---------+
id is a continuous increasing primary key starting from 1.
Examples
Example 1
Input Table:
Seat table:
+----+---------+
| id | student |
+----+---------+
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
| 5 | Jeames |
+----+---------+
Expected Output:
+----+---------+
| id | student |
+----+---------+
| 1 | Doris |
| 2 | Abbot |
| 3 | Green |
| 4 | Emerson |
| 5 | Jeames |
+----+---------+
SQL Solution
SELECT
CASE
WHEN id % 2 = 1 AND id = (SELECT MAX(id) FROM Seat) THEN id
WHEN id % 2 = 1 THEN id + 1
ELSE id - 1
END AS id,
student
FROM Seat
ORDER BY id;
Problem Info
DifficultyMEDIUM
Topics
case-whensubqueryorder-by
Reference Links