leetcode-626-Exchange-Seats

描述


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
+---------+---------+
| id | student |
+---------+---------+
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
| 5 | Jeames |
+---------+---------+

For the sample input, the output is:

1
2
3
4
5
6
7
8
9
+---------+---------+
| 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.

分析


将表中的奇数行与偶数行交换位置,如果表的总行数是奇数,最后一行不变。

SQL 的 IF 函数类似于 A? B: C。

解决方案1(MySQL)


1
2
3
# Write your MySQL query statement below
select if(id < (select count(*) from seat), if(id mod 2 = 0, id-1, id+1), if(id mod 2 = 0, id-1, id)) as id, student
from seat order by id asc;

题目来源