This Leetcode problem Exchange Seats LeetCode Solution is done in SQL.
List of all LeetCode Solution
![Exchange Seats LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Exchange Seats LeetCode Solution
Table of Contents
Problem Statement
Column Name | Type |
id | int |
student | varchar |
Seat
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. id is a continuous increment.
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:
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 Solution MySQL
select
if(
mod(id, 2) = 0,
id - 1,
if(
id < (
select
max(id)
from
seat
),
id + 1,
id
)
) as id,
student
from
seat
order by
id;
Code language: SQL (Structured Query Language) (sql)