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.
The ID sequence always starts from 1 and increments continuously.
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.
id 가 홀수인 학생(student) 와 짝수인 학생을 바꾸는 문제. 조건에는 마지막 학생은 바꾸지 않는다고 되어 있다.
생각보다 단순한거 같으면서도 쿼리가 조금 복잡하게 짜여진거 같다.
select id
,case
when id % 2 = 1 and id + 1 <= (select max(id) from seat) then
(select student from seat where id = s.id +1)
when id % 2 = 0 then
(select student from seat where id = s.id -1)
else student
end as student
from seat s
order by id;
case 문
;
when
:
id % 2 = 1 홀수일 경우에서 id +1 을 해주어 다음 학생을 찾았다.
<= (select max(id) from seat
:
서브쿼리로 최대 크기의 id, 즉 마지막 5번 학생까지만 찾는 조건
(select student from seat where id = s.id + 1)
:
서브쿼리로 where 조건절에서 짝수 학생을 찾아내어 홀수 학생과 자리를 바꿔준다.
when
:
마찬가지로 id % 2 = 0 짝수일 경우의 학생을 찾았다.
(select student from seat where id = s.id - 1)
:
where 조건절에서 홀수 학생을 찾아내어 짝수 학생과 자리를 바꿔준다.
다른 사람의 풀이중에 if 문을 활용하여 만든 쿼리도 있었다.
-- 다른 사람의 풀이
SELECT IF (id < (SELECT MAX(id) FROM Seat),
IF(id % 2 = 0, id - 1, id + 1),
IF(id % 2 = 0, id - 1, id)
) AS id, student
FROM Seat
ORDER BY id;