问题描述:
交换id奇数、偶数位置,如果id最后一位是奇数,那么它不换。
输入:
Seat 表:
±—±--------+
| 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. # 第一种写法:窗口函数写法
select rank() over (order by (id-1)^1) from seat
逻辑与非的写法,我理解是id-1 ^是异或运算符。
2 第二种写法:mod函数
mod函数内部除法
select (
case when mod(id,2) = 1 and counts = id then id //最后一位
when mod(id,2) = 1 and counts != id then id + 1//奇数
when mod(id,2) = 0 then id - 1 end //偶数
) as id,student
from
(select count(*) as counts from seat) as seat_count,seat
order by
id