inblog logo
|
silver
    SQL문제풀기

    [SQL문제풀기] Exchange Seats

    silver's avatar
    silver
    Nov 14, 2025
    [SQL문제풀기] Exchange Seats
    Contents
    문제MySQL

    문제

    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/submissions/1842548128/?envType=study-plan-v2&envId=top-sql-50
    Exchange Seats - LeetCode

    MySQL

    내가 작성한 정답

    select case when id%2=0 then id-1 when id%2=1 and id = (select max(id) from Seat) then id else id+1 end id, student from Seat order by 1;
    Share article

    silver

    RSS·Powered by Inblog