inblog logo
|
stupefyee
    SQL문제풀기

    [SQL 문제 풀이] Exchange Seats (교환석)

    Stupefyee's avatar
    Stupefyee
    May 20, 2025
    [SQL 문제 풀이] Exchange Seats (교환석)
    Contents
    내가 작성한 쿼리
    Exchange Seats - LeetCode
    Can you solve this real interview question? Exchange Seats - Table: Seat +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | student | varchar | +-------------+---------+ id is the primary key (unique value) column for this table. Each row of this table indicates the name and the ID of a student. The ID sequence always starts from 1 and increments continuously.   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.   Example 1: Input: Seat table: +----+---------+ | id | student | +----+---------+ | 1 | Abbot | | 2 | Doris | | 3 | Emerson | | 4 | Green | | 5 | Jeames | +----+---------+ Output: +----+---------+ | id | student | +----+---------+ | 1 | Doris | | 2 | Abbot | | 3 | Green | | 4 | Emerson | | 5 | Jeames | +----+---------+ Explanation: Note that if the number of students is odd, there is no need to change the last one's seat.
    Exchange Seats - LeetCode
    https://leetcode.com/problems/exchange-seats/description/
    Exchange Seats - LeetCode
    notion image
    연속되는 두 학생의 좌석 ID를 바꾸는 솔루션을 작성합니다. 학생 수가 홀수인 경우 마지막 학생의 ID는 변경되지 않습니다. ID 순으로 정렬된 결과 테이블을 오름차순으로 반환합니다.
     

    내가 작성한 쿼리

    MySQL, Oracle

    SELECT CASE -- id가 홀수이고 +1한 값이 범위 내라면 WHEN MOD(id, 2) = 1 AND id + 1 <= (SELECT MAX(id) FROM Seat) THEN id + 1 -- id가 짝수 WHEN MOD(id, 2) = 0 THEN id - 1 ELSE id END AS id, student FROM Seat ORDER BY id;
    Share article
    Contents
    내가 작성한 쿼리

    stupefyee

    RSS·Powered by Inblog