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?
+---------+---------+
| 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.
解题思路
交换seat
用交换Id
实现,1与2交换,3与4交换… 最后的Id
为奇数时,不交换。
先增加一个临时表,字段有id
, student
, max_id
, 其中max_id
列为常量,当
(1)奇数id(且id != max_id)交换时,id+1;
(2)偶数id交换时,id-1;
(3)max_Id为奇数时,id不变。
实现代码
#方法一
select
(case
when mod(id, 2) = 1 and id != (select max(id) from seat) then id + 1
when mod(id, 2) = 0 then id -1
else id
end) as id, student
from seat
order by id;
#方法二
select
(case
when id % 2 = 1 and id != max_id then id + 1
when id % 2 = 0 then id - 1
when id = max_id then id #该条语句不可省略
end) as id, student
from
(select id, student, (select max(id) from seat) as max_id from seat) a #a为表的别名
order by id;