Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ Have a good contributing!
- [184. Department Highest Salary](./leetcode/medium/184.%20Department%20Highest%20Salary.sql)
- [570. Managers with at Least 5 Direct Reports](./leetcode/medium/570.%20Managers%20with%20at%20Least%205%20Direct%20Reports.sql)
- [602. Friend Requests II: Who Has the Most Friends](./leetcode/medium/602.%20Friend%20Requests%20II:%20Who%20Has%20the%20Most%20Friends.sql)
- [626. Exchange Seats](./leetcode/medium/626.%20Exchange%20Seats.sql)
- [1045. Customers Who Bought All Products](./leetcode/medium/1045.%20Customers%20Who%20Bought%20All%20Products.sql)
- [1070. Product Sales Analysis III](./leetcode/medium/1070.%20Product%20Sales%20Analysis%203.sql)
- [1158. Market Analysis 1](./leetcode/medium/1158.%20Market%20Analysis%201.sql)
Expand Down
43 changes: 43 additions & 0 deletions leetcode/medium/626. Exchange Seats.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
Question 626. Exchange Seats
Link: https://leetcode.com/problems/exchange-seats/description/?envType=study-plan-v2&envId=top-sql-50

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.
*/

SELECT
s.id,
(CASE
WHEN s.id % 2 = 0 THEN s1.student
WHEN s3.student IS NULL THEN s.student
WHEN s.id % 2 = 1 THEN s3.student
END) AS student
FROM Seat AS s
LEFT JOIN
Seat AS s1
ON s.id = (
SELECT MIN(s2.id) FROM Seat AS s2
WHERE s1.id < s2.id
)
LEFT JOIN
Seat AS s3
ON s.id = (
SELECT MAX(s4.id) FROM Seat AS s4
WHERE s3.id > s4.id
)