626. 换座位

小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。

其中纵列的 id 是连续递增的

小美想改变相邻俩学生的座位。

你能不能帮她写一个 SQL query 来输出小美想要的结果呢?

 

示例:

+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Abbot   |
|    2    | Doris   |
|    3    | Emerson |
|    4    | Green   |
|    5    | Jeames  |
+---------+---------+

假如数据输入的是上表,则输出结果如下:

+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Doris   |
|    2    | Abbot   |
|    3    | Green   |
|    4    | Emerson |
|    5    | Jeames  |
+---------+---------+

解析:

对所有数据进行拆分,1、2互换,3、4互换,最后一个是奇数的不动,然后就分成三块来写,第一块就是id为偶数的,id-1就相当于和奇数的互换了,第二块是id为奇数的,id+1就相当于和偶数的互换了,最后一块是最后一个为奇数的,不换,然后三块合并排序就出来结果了。

select s.id,s.student from
(
select id-1 as id ,student from seat where mod(id,2)=0
union
select id+1 as id,student from seat where mod(id,2)=1 and id !=(select count(*) from seat)
union
select id,student from seat where mod(id,2)=1 and id = (select count(*) from seat)
) s order by id;

拓展:当原id为奇数时,交换座位后的id变为id+1,当原id为偶数时,交换座位后的id变为id-1,

注意:学生人数为奇数时,最后一个学生的id不变,故应当用子查询确定学生的人数,然后分情况讨论。

select (case  
      when mod(id,2)!=0 and id!=counts then id+1  
      when mod(id,2)!=0 and id=counts then id  
      else id-1 end)as id,student  
      from seat,(select count(*)as counts from seat)as seat_counts  
                order by id;  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值