[leetcode]626. Exchange Seats

hy_jin·2023년 11월 22일

Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids.

The column id is continuous increment.

Mary wants to change seats for the adjacent students.

Can you write a SQL query to output the result for Mary?

https://leetcode.com/problems/exchange-seats/

정답

SELECT 	ROW_NUMBER() OVER (ORDER BY u.id) as id
        , u.student 
FROM (
    SELECT id+1 as id, student
    FROM Seat
    WHERE mod(id,2)=1
    UNION ALL
    SELECT id-1 as id, student
    FROM Seat
    WHERE mod(id,2)=0
) u
order by id

풀이

나누고 UNION ALL을 통해 해결하는 방법으로 풀이하였다.
근데 문제를 자세히 읽어보니 마지막 값을 없애는게 아닌 본인의 id로 그대로 남겨야했기에 그걸 조건에 추가해야했다.
그래서 이 풀이는 좋은 풀이는 아닌듯 하다.

FROM 절에 case when을 넣어 then으로 값을 변형시키는 풀이가 더 좋을 듯하다

profile
천천히 꾸준히

0개의 댓글