[LeetCode - Medium] Exchange Seats 연속된 두 행의 정보를 바꾸기 ( CASE 문에서 윈도우 함수 LAG/LEAD 사용하기, MOD, COALESCE )

LeetCode 626. Exchange Seats

Problem

Difficulty : Medium

Write an SQL query 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.

My Solution

My Logic

  • 두 쌍의 연속된 id 즉, (홀수 id, 짝수 id) 의 위치를 바꿔야한다.
  • 홀수 짝수 조건문 작성을 위해 MOD() 를 사용한다.
  • 윈도우 함수로 id를 바꾼다.
    • 홀수의 경우, 아래 행에서 id를 끌어와야하므로 LAG
    • 짝수의 경우, 위의 행에서 id를 끌어와야하므로 LEAD
  • 학생의 숫자가 홀수인 경우, 마지막 id는 교환할 숫자가 없어 윈도우 함수 결과가 NULL이 되는데, 원래 id 그대로 출력하기 위해 COALESCE() 를 사용한다.
-- OUTPUT : id | student
SELECT 
    CASE 
        WHEN MOD(id, 2) = 0 THEN LAG(id) OVER(ORDER BY id)
        WHEN MOD(id, 2) != 0 THEN COALESCE(LEAD(id) OVER(ORDER BY id), id)
        END AS `id`,
    student
FROM Seat
-- Return the result table ordered by id in ascending order
ORDER BY id

Lessons Learned

홀수, 짝수 조건을 활용해야하는 경우 ⇒ MOD() 나머지 조건 활용