返回介绍

solution / 0600-0699 / 0626.Exchange Seats / README_EN

发布于 2024-06-17 01:03:36 字数 2809 浏览 0 评论 0 收藏 0

626. Exchange Seats

中文文档

Description

Table: Seat

+-------------+---------+
| Column Name | Type  |
+-------------+---------+
| id      | int   |
| student   | varchar |
+-------------+---------+
id is the primary key (unique value) column for this table.
Each row of this table indicates the name and the ID of a student.
id is a continuous increment.

 

Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped.

Return the result table ordered by id in ascending order.

The result format is in the following example.

 

Example 1:

Input: 
Seat table:
+----+---------+
| id | student |
+----+---------+
| 1  | Abbot   |
| 2  | Doris   |
| 3  | Emerson |
| 4  | Green   |
| 5  | Jeames  |
+----+---------+
Output: 
+----+---------+
| id | student |
+----+---------+
| 1  | Doris   |
| 2  | Abbot   |
| 3  | Green   |
| 4  | Emerson |
| 5  | Jeames  |
+----+---------+
Explanation: 
Note that if the number of students is odd, there is no need to change the last one's seat.

Solutions

Solution 1

# Write your MySQL query statement below
SELECT s1.id, COALESCE(s2.student, s1.student) AS student
FROM
  Seat AS s1
  LEFT JOIN Seat AS s2 ON (s1.id + 1) ^ 1 - 1 = s2.id
ORDER BY 1;

Solution 2

# Write your MySQL query statement below
SELECT
  id + (
    CASE
      WHEN id % 2 = 1
      AND id != (SELECT MAX(id) FROM Seat) THEN 1
      WHEN id % 2 = 0 THEN -1
      ELSE 0
    END
  ) AS id,
  student
FROM Seat
ORDER BY 1;

Solution 3

# Write your MySQL query statement below
SELECT
  RANK() OVER (ORDER BY (id - 1) ^ 1) AS id,
  student
FROM Seat;

Solution 4

# Write your MySQL query statement below
SELECT
  CASE
    WHEN id & 1 = 0 THEN id - 1
    WHEN ROW_NUMBER() OVER (ORDER BY id) != COUNT(id) OVER () THEN id + 1
    ELSE id
  END AS id,
  student
FROM Seat
ORDER BY 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文