관리 메뉴

오늘도 배운다

626. Exchange Seats / LeetCode, SQL, MySQL 본문

코딩테스트연습(SQL)

626. Exchange Seats / LeetCode, SQL, MySQL

LearnerToRunner 2023. 3. 10. 21:01

문제

source: LeetCode
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.

Return the result table ordered by id in ascending order.

 

 

 

 

제출답안(MySQL)

SELECT 
    ROW_NUMBER() OVER (ORDER BY FLOOR((id+1)/2), MOD(id, 2)) AS id, 
    student
FROM seat

 

 

 

풀이(MySQL)

더보기

홀수, 짝수 id 한 쌍 씩 구분 / 쌍 내에서 짝수를 구분할 수 있는 가상의 칼럼 생성

FLOOR((id+1)/2)

>> 1, 2번 행의 값은 0 을 반환하고 3, 4번 행의 값은 1을 반환함

MOD(id, 2)

>> id가 홀수이면 1, 짝수이면 2를 반환함

 

짝수 구분하는 수와 홀짝을 구분하는 숫자를 기준으로 정렬 후 row 번호를 정렬된 순서대로 부

 

 

SELECT 
    ROW_NUMBER() OVER (ORDER BY FLOOR((id+1)/2), MOD(id, 2)) AS id, 
    student
FROM seat

>>

 

 

 

문제 바로가기(MySQL)

728x90
Comments