[Leet Code] 626. Exchange Seats

Donghyun·2024년 10월 28일
0

Code Kata - SQL

목록 보기
62/62
post-thumbnail

링크: https://leetcode.com/problems/exchange-seats/

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를 바꿔라.

  • 학생 수가 홀수라면, 마지막 학생의 id는 그대로 출력.
  • 결과는 id를 기준으로 오름차순 정렬.

최종코드

SELECT 
    CASE WHEN MOD(id, 2) = 1 AND id = (SELECT MAX(id) FROM Seat) THEN id
         WHEN MOD(id, 2) = 0 THEN id - 1
         ELSE id + 1
         END AS id,
    student
FROM Seat
ORDER BY id ASC;

설명

SELECT 
    CASE WHEN MOD(id, 2) = 1 AND id = (SELECT MAX(id) FROM Seat) THEN id
         WHEN MOD(id, 2) = 0 THEN id - 1
         ELSE id + 1
         END AS id,
    student
  • 첫 번째 케이스: id가 홀수이고, 가장 마지막 id의 학생은 id를 그대로 두는 것.
  • 두 번째 케이스: id가 짝수인 경우 해당 id값에서 1을 빼주고,
  • 세 번째 케이스: 첫 번째, 두 번째 케이스에 해당하지 않는 id가 홀수인 경우에는 id 값에서 1을 더해준다.
profile
데이터분석 공부 일기~!

0개의 댓글

관련 채용 정보