ror_coding

[LeetCode] 626. Exchange Seats 본문

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

'Coding Test > SQL' 카테고리의 다른 글

[LeetCode] 1321. Restaurant Growth  (0) 2025.07.19
[LeetCode] 1341. Movie Rating  (0) 2025.07.19
[LeetCode] 1907. Count Salary Categories  (1) 2025.07.19
[LeetCode] 1934. Confirmation Rate  (0) 2025.07.13
[LeetCode] 176. Second Highest Salary  (0) 2025.07.13