表: Seat
+————-+———————+
| Column Name | Type |
+————-+———————+
| id | int |
| name | varchar |
+————-+———————+
Id是该表的主键列。
该表的每一行都表示学生的姓名和ID。
Id是一个连续的增量。
编写SQL查询来交换每两个连续的学生的座位号。如果学生的数量是奇数,则最后一个学生的id不交换。
按 id 升序 返回结果表。
来源:力扣(LeetCode)
从上到下,两个学生之间交换一次,总数在团队中统计,不交换。
[En]
From top to bottom, there is one exchange between two students, and the total is counted and not exchanged in the team.
思路:一般是判断当前id,这个是不是最后的一个学生,再通过 窗口函数 :
往前取N行 lag(参照行,行数N,default值)
往后取N行 lead()
转换查询出来的位置;
select id,
if(i %2 = 0,last,next) student
from (
select id,student,
lag() over(order by id ) last
lead() over(order by id) next
from 表
) ss
力扣上面有人用位运算来排序直接输出,直接囊括了边界值
select rank() over(order by (id -1)^1) as id,student from 表;
在id值中,对于每个偶数减少2(偶数先减为奇数,该数二进制末尾是1,异或运算会被变成0,相当于-2)
对于每个奇数,它被缩减为偶数,末尾为0。在与1的运算之后,加1,等于相同的数字,因此交换相邻的奇数和偶数。
[En]
For each odd number, it is reduced to an even number, and the end is 0. After the operation with 1, 1 is added, which is equal to the same number, so the adjacent odd and even numbers are exchanged.
Original: https://www.cnblogs.com/aLiuLiu/p/16651270.html
Author: 阿榴
Title: SQL中的排座位问题
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/504900/
转载文章受原作者版权保护。转载请注明原作者出处!