编写一个查询来切换相邻学生的ID?这是示例输入

ibrsph3r  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(174)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

两年前关门了。
改进这个问题
1) 写一个查询来切换相邻学生的ID?这是示例输入。

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

对于样本输入,输出为:

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

请注意,如果座位总数为奇数,则最后一个座位的id保持不变。

iq3niunx

iq3niunx1#

你可以在下面试试
演示

select id,coalesce(bname,aname) as Name from
(
select A.id,A.name as aname,B.name as bname
from
(select id,name
from cte1 where id%2=1
)A left join 
(select id,name
from cte1 where id%2=0
)B on A.id+1=B.id

union all

select A.id,A.name,B.name
from
(select id,name
from cte1 where id%2=0
)A left join 
(select id,name
from cte1 where id%2=1
)B on A.id=B.id+1
)X order by id

输出:

id  Name
1   Doris
2   Abbot
3   Green
4   Emerson
5   Jeames
qni6mghb

qni6mghb2#

如果你的身份证被订购了这会帮你的,

SELECT a.id,b.Name
 from
(SELECT [id],[Name]
  FROM [Table]
  where mod([id],2)=1) a
  inner join 
  (SELECT [id],[Name]
  FROM [Table]
  where mod([id],2)=0) b
  on a.id+1=b.id

  UNION

  select b.id,a.Name
 from
(SELECT [id],[Name]
  FROM [Table]
  where mod([id],2)=1) a
  inner join 
  (SELECT [id],[Name]
  FROM [Table]
  where mod([id],2)=0) b
  on a.id+1=b.id

相关问题