반응형
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
- 그 외: 즉, 마지막 홀수 번호인 경우 → 자리 그대로
반응형
'Computer Science > SQL' 카테고리의 다른 글
SQL | LeetCode 1321. 7일 단위 평균으로 매출 분석하기 (0) | 2025.06.03 |
---|---|
SQL | LeetCode 1341. 집계(Aggregation), 날짜 필터링, 정렬 및 서브쿼리 활용 (1) | 2025.06.02 |
SQL | LeetCode 1978. 조건에 맞는 직원 찾기 (NOT IN) (1) | 2025.05.31 |
SQL | LeetCode 1907. Salary 범주별 계좌 수 세기 (UNION vs. UNION ALL) (0) | 2025.05.30 |
SQL | LeetCode 1204. 버스 정원 제한에 따라 탈 수 있는 마지막 사람 구하기 (0) | 2025.05.29 |