Table: Seat
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| student | varchar |
+-------------+---------+
id is the primary key (unique value) column for this table.
Each row of this table indicates the name and the ID of a student.
The ID sequence always starts from 1 and increments continuously.
Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped.
Return the result table ordered by id in ascending order.
The result format is in the following example.
Example 1:
Input:
Seat table:
+----+---------+
| id | student |
+----+---------+
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
| 5 | Jeames |
+----+---------+
Output:
+----+---------+
| id | student |
+----+---------+
| 1 | Doris |
| 2 | Abbot |
| 3 | Green |
| 4 | Emerson |
| 5 | Jeames |
+----+---------+
Explanation:
Note that if the number of students is odd, there is no need to change the last one's seat.
SELECT
CASE
WHEN id % 2 = 1 AND id + 1 <= (SELECT MAX(id) FROM Seat) THEN id + 1
#id가 홀수인 경우와 id + 1가 max_id보다 작거나 같은경우 id에 1을 더한다.
WHEN id % 2 = 0 THEN id - 1
# id가 짝수인 경우 id에 1을 뺀다.
ELSE id
# 그 외에는 id를 출력한다.
END AS id,
student
FROM
Seat
ORDER BY
id;
# id를 오름차순으로 정렬한다.
-- id = 1 (홀수, 1 + 1 = 2) => 새로운 id = 2
-- id = 2 (짝수, 2 - 1 = 1) => 새로운 id = 1
-- id = 3 (홀수, 3 + 1 = 4) => 새로운 id = 4
-- id = 4 (짝수, 4 - 1 = 3) => 새로운 id = 3
-- id = 5 (홀수, 5 + 1 = 6, 최대 id가 5이므로 ELSE 구문 적용) => 새로운 id = 5