美文网首页
SQL in leetcode——medium篇

SQL in leetcode——medium篇

作者: 迷糊的小竹笋 | 来源:发表于2019-03-14 20:39 被阅读0次

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 #顺序

相关文章

网友评论

      本文标题:SQL in leetcode——medium篇

      本文链接:https://www.haomeiwen.com/subject/vyqhmqtx.html