Coding Test/SQL
[LeetCode] 626. Exchange Seats
ro_rdil_31
2025. 7. 19. 14:34
728x90
row_number() 로 홀짝을 구별하여 id에서 빼거나 더한 값을 id로 부여합니다.
따라서 이름은 고정, id만 바뀜.
Question

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.

Code
select
row_number() over(order by if(id % 2 = 0, id - 1, id + 1)) as id
, student
from seat
order by 1;
Code (My Code)
select
case
when (id%2 = 1) and (id+1 in (select id from seat)) then id + 1
when (id%2 = 0) then id - 1
else id
end as id
, student
from seat
order by 1
;
My Code
728x90