Leetcode) No.626 [Exchange Seats]
본문 바로가기
Data Base/Leetcode

Leetcode) No.626 [Exchange Seats]

by 조훈이 2021. 9. 4.

Leetcode) No.626 [Exchange Seats]


  문제 

Exchange Seats - LeetCode

 

Exchange Seats - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


  설명 

#UNION
#SUB_QUERY
#ORDER

  이와 같이 id가 가리키는 student가 변경되어야 한다. 홀수 id 를 만드는 Sub query 와 짝수 id 를 만드는 Sub query 를 하나씩 작성하여 UNION 을 한 뒤, UNION 이 된 table 을 id 를 기준으로 오름차순으로 정렬을 하였다.


  Code 

더보기
SELECT main.id, main.student
FROM (
    (SELECT id - 1 AS id, student 
    FROM seat
    WHERE id & 1 = 0)	#짝수인 경우
    UNION
    (SELECT 
        (CASE WHEN id < (SELECT MAX(id)
                         FROM seat)
              THEN id + 1	#현재 id 값이 행의 끝이 아니라면
              ELSE id		#현재 id 값이 행의 끝 이라면
              END
         ) AS id, student
    FROM seat
    WHERE id & 1 = 1)	#홀수인 경우
) AS main
ORDER BY main.id ASC;
728x90

'Data Base > Leetcode' 카테고리의 다른 글

Leetcode) No.262 [Trips and Users]  (0) 2022.04.04
Leetcode) No.180 [Consecutive Numbers]  (0) 2021.09.03
Leet) No.175 [Combine Two Tables]  (0) 2021.08.31
Leet) No.1179 [Reformat Department Table]  (0) 2021.08.30

댓글