https://leetcode.com/problems/exchange-seats/
交换相邻学生的id,很容易想到,id为基数的:id+=1;id为偶数:id-=1.需要注意的是,如果学生人数为奇数,最后一名同学是不能+1的。
步骤
- 首先考虑统计学生个数
select count(*) as counts from seat
- 利用case语句写赋值逻辑
case
when mod(id, 2) != 0 and id != counts then id += 1
when mod(id, 2) != 0 and id == counts then id
when mod(id, 2) == 0 then id -= 1
end
注意理解,这部分是id。
- 整体逻辑串起来
select
(case
when mod(id, 2) != 0 and id != counts then id + 1
when mod(id, 2) != 0 and id = counts then id
when mod(id, 2) = 0 then id - 1
end) as id, student
from seat, (select count(*) as counts from seat) as seat_count #seat_count为table
order by id asc #顺序
网友评论