Mary is a teacher in a middle school and she has a table
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.
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 tORDER BY id;
Approach: Using Case
Mysql
SELECT ( CASEWHEN id%2 != 0 AND id != counts THEN id+1WHEN id%2 != 0 AND id = counts THEN idELSE id-1END) AS id, studentFROM seat, (select count(*) as counts from seat)AS seat_countsORDER BY id ASC;
Oracle:
SELECT( CASE WHEN MOD(id,2) != 0 AND id != counts THEN id+1WHEN MOD(id,2) != 0 AND id = counts THEN idELSE id-1END) AS id, studentFROM seat, (select count(a.id) as counts from seat a)ORDER BY id ASC
No comments:
Post a Comment