SQL in leetcode——medium篇

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 #顺序
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容