[SQL]

LeetCode 코딩 테스트 - Exchange Seats(LV.Medium)

indongspace 2025. 3. 2. 00:43

 

 

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.

 

테이블: Seat

+-------------+---------+
| 컬럼 이름 | 타입 |
+-------------+---------+
| id | int |
| student | varchar |
+-------------+---------+

id는 기본 키(고유한 값)이며, 항상 1부터 시작하여 연속적으로 증가합니다.

모든 연속된 두 학생의 좌석 id를 서로 바꾸는 SQL 쿼리를 작성하세요. 학생 수가 홀수인 경우 마지막 학생의 id는 변경하지 않습니다.

결과 테이블은 id 기준 오름차순으로 정렬되어야 합니다.

결과 형식은 다음 예제를 따릅니다.

예제 1:

입력:
Seat 테이블:

+----+---------+
| id | student |
+----+---------+
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
| 5 | Jeames |
+----+---------+

출력:

+----+---------+
| id | student |
+----+---------+
| 1 | Doris |
| 2 | Abbot |
| 3 | Green |
| 4 | Emerson |
| 5 | Jeames |
+----+---------+

설명:
학생 수가 홀수인 경우 마지막 학생의 좌석은 변경하지 않습니다.

 

# 좌석인 id는 고정이고, student를 왔다갔다 옮겨야 한다. 
SELECT
    id,
    CASE
    	# 1. 좌석 id가 짝수이면 앞 사람을 가져온다.
        WHEN id % 2 = 0 THEN LAG(student) OVER()
        # 2. 좌석 id가 홀수이면 뒷 사람을 가져온다. 하지만 LEAD값이 NULL인 경우(=마지막 좌석) 학생은 자리를 옮기지 않는다.
        ELSE COALESCE(LEAD(student) OVER(), student)
    END AS student 
FROM seat