【LeetCode】626.换座位

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wal1314520/article/details/80117658

626.换座位

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

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

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

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


用到的表和数据SQL:

Create table If Not Exists seat(id int, studentvarchar(255));
Truncate table seat;
insert into seat (id, student) values ('1','Abbot');
insert into seat (id, student) values ('2','Doris');
insert into seat (id, student) values ('3','Emerson');
insert into seat (id, student) values ('4','Green');
insert into seat (id, student) values ('5','Jeames');

答案:

方法一:按题目的要求,对所有数据进行拆分,12互换,34互换,最后一个是奇数的不动,然后就分成三块来写,第一块就是id为偶数的,id-1就相当于和奇数的互换了,第二块是id为奇数的,id+1就相当于和偶数的互换了,最后一块是最后一个为奇数的,不换,然后三块合并排序就出来结果了。

select s.id , s.student from
(
select id-1 as id ,student from seat wheremod(id,2)=0
union
select id+1 as id,student from seat wheremod(id,2)=1 and id !=(select count(*) from seat)
union
select id,student from seat where mod(id,2)=1and 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;

写的比较粗糙,有不理解的可以扫描二维码加QQ群找我解答。


 


猜你喜欢

转载自blog.csdn.net/wal1314520/article/details/80117658