# Write your MySQL query statement below
with report as (
select
id,
if(mod(id,2)=1,lead(student) over (order by id),lag(student) over (order by id)) student
from Seat
)
select
id,
if(isnull(
student
),(select student from Seat where id=report.id),student) as student
from report
order by id asc;
查询lead、lag文档可知:
这里我们直接用lead设置最后一个奇数项的默认值即可,比使用if isnull判断简单很多。
select
id,
if(mod(id,2)=1,lead(student,1,student) over (order by id),lag(student) over (order by id)) student
from Seat
with maxId as (
select max(id) mid from Seat
)
select
if(
mod(id,2)=1,
if(id=maxId.mid,id,id+1),
id-1) as id,
student
from Seat,maxId
order by id asc;
上述写法等价于子查询写法:
select
if(
mod(id,2)=1,
if(id=(select max(id) from Seat),id,id+1),
id-1) as id,
student
from Seat
order by id asc;