리트코드(leetcode) 문제풀이 : Exchange Seats (10/8)

백엔ㄷ현·2024년 10월 8일
0

Table: Seat

Column NameType
idint
studentvarchar

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:

idstudent
1Abbot
2Doris
3Emerson
4Green
5Jeames

Output:

idstudent
1Doris
2Abbot
3Green
4Emerson
5Jeames

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;
profile
매일매일 공부한 내용과 코드 기록하겠습니다

0개의 댓글