Exchange Seats Problem


Description

LeetCode Problem 626.

Mary is a teacher in a middle school and she has a table seat storing students’ names and their corresponding seat ids.

The column id is continuous increment.

Mary wants to change seats for the adjacent students.

Can you write a SQL query to output the result for Mary?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Abbot   |
|    2    | Doris   |
|    3    | Emerson |
|    4    | Green   |
|    5    | Jeames  |
+---------+---------+
For the sample input, the output is:

+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Doris   |
|    2    | Abbot   |
|    3    | Green   |
|    4    | Emerson |
|    5    | Jeames  |
+---------+---------+

Note: If the number of students is odd, there is no need to change the last one’s seat.


MySQL Solution

1
2
3
4
5
6
7
8
9
10
11
12
select
    (case
        when mod(id, 2) != 0 and counts != id then id + 1
        when mod(id, 2) != 0 and counts = id then id
        else id - 1
    end) as id,
    student
from
    seat,
    (select count(*) as counts
    from seat) as seat_counts
order by id 




Related Posts

Exchange Seats Problem

LeetCode 626. Mary is a teacher in a middle school...

Customers Who Bought All Products Problem

LeetCode 1045. Write an SQL query for a report that...

Biggest Single Number Problem

LeetCode 619. Table my_numbers contains many numbers in column num...

Not Boring Movies Problem

LeetCode 620. X city opened a new cinema, many people...

Swap Salary Problem

LeetCode 627. Given a table salary, such as the one...

Actors And Directors Who Cooperated At Least Three Times Problem

LeetCode 1050. Write a SQL query for a report that...