Computer Science/SQL
SQL | LeetCode 626. ID 기준으로 행 순서 재배치하기 (CASE WHEN)
올리브한입
2025. 6. 1. 07:08
반응형
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.
ID는 1부터 시작해서 연속되므로,
- 짝수 id인 학생은 바로 앞자리(id - 1) 로 이동
- 홀수 id인 학생은 바로 뒷자리(id + 1) 로 이동
- 단, 뒷자리가 존재하지 않는다면 (예: 마지막 홀수 자리), 그대로 유지합니다.
select
case when id % 2 = 1 and id + 1 <= (SELECT COUNT(*) FROM Seat) then id + 1
when id % 2 = 0 then id - 1
else id
end as id,
student
from seat
order by id
id + 1 <= (SELECT COUNT(*) FROM Seat)는 밑을 의미합니다.
- id = 1 → 1 + 1 = 2 ≤ 5 ✅ → swap 가능
- id = 3 → 3 + 1 = 4 ≤ 5 ✅ → swap 가능
- id = 5 → 5 + 1 = 6 ❌ → swap ❌ → 자기 자리 유지
CASE
WHEN id % 2 = 1 AND id + 1 <= (SELECT COUNT(*) FROM Seat) THEN id + 1
- 홀수 번째 학생이고, 다음 id가 테이블 안에 존재하면 → 다음 자리로 이동
WHEN id % 2 = 0 THEN id - 1
- 짝수 번째 학생이면 → 이전 자리로 이동 (홀수와 스왑)
ELSE id
- 그 외: 즉, 마지막 홀수 번호인 경우 → 자리 그대로
반응형