Exchange Seats

Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids.
The column id is a continuous increment.
Mary wants to change seats for the adjacent students.
Write a SQL query to output the result for Mary.

Example:

Table: Seat
+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Abbot   |
|    2    | Doris   |
|    3    | Emerson |
|    4    | Green   |
|    5    | Jeames  |
+---------+---------+
Result:
+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Doris   |
|    2    | Abbot   |
|    3    | Green   |
|    4    | Emerson |
|    5    | Jeames  |
+---------+---------+

Approach: Using IF

Mysql


SELECT IF(cnt % 2 = 1 AND id = cnt, id, 
        IF(id % 2 = 1, id + 1, id - 1)) AS id, student FROM seat,
(SELECT COUNT(*) AS cnt FROM seat) AS t
ORDER BY id;

Approach: Using Case

Mysql


SELECT ( CASE
            WHEN id%2 != 0 AND id != counts THEN id+1
            WHEN id%2 != 0 AND id = counts THEN id
            ELSE id-1
        ENDAS id, student
FROM seat, (select count(*) as counts from seat) 
AS seat_counts
ORDER BY id ASC;

Oracle:

SELECT 
CASE WHEN MOD(id,2) != 0 AND id != counts THEN id+1
            WHEN MOD(id,2) != 0 AND id = counts THEN id
            ELSE id-1
        ENDAS id, student
FROM seat, (select count(a.id) as counts from seat a) 
ORDER BY id ASC


No comments:

Post a Comment