문제
There is a queue of people waiting to board a bus. However, the bus has a weight limit of 1000 kilograms, so there may be some people who cannot board.
Write a solution to find the person_name of the last person that can fit on the bus without exceeding the weight limit. The test cases are generated such that the first person does not exceed the weight limi
Table
" 순서대로 버스를 탔을 때, 몸무게가 1000kg 이 넘을 때, 하차해야 한다. 이때, 마지막으로 탈 수 있는 사람의 이름을 확인하시오."
정답코드
SELECT person_name
FROM(
SELECT *
, SUM(weight) OVER (ORDER BY turn) AS sum_weight
FROM Queue
) t
WHERE sum_weight <= 1000
ORDER BY sum_weight DESC
LIMIT 1
풀이과정
1. 먼저 SUM() OVER() 윈도우 함수를 활용하여 turn 별로 누적 몸무게의 합을 구한다.
** SUM() OVER( ORDER BY) 는 누적합계 합을 구할 수 있는 윈도우 함수
SELECT *
, SUM(weight) OVER (ORDER BY turn) AS sum_weight
FROM Queue
2. sum_weight 값이 1000 이하인 person_name을 구한다.
SELECT person_name
FROM(
SELECT *
, SUM(weight) OVER (ORDER BY turn) AS sum_weight
FROM Queue
) t
WHERE sum_weight <= 1000
3. ORDER BY를 활용하여 내림차순으로 정렬한 후, 가장 첫번째 행의 값을 선택한다. (1000kg 되기 직전의 사람)
SELECT person_name
FROM(
SELECT *
, SUM(weight) OVER (ORDER BY turn) AS sum_weight
FROM Queue
) t
WHERE sum_weight <= 1000
ORDER BY sum_weight DESC
LIMIT 1
'취준 > 코팅 테스트' 카테고리의 다른 글
[LeetCode] - 1965. Employees With Missing Information (0) | 2024.04.09 |
---|---|
585. Investments in 2016 (0) | 2024.04.09 |
[LeetCode] 1484. Group Sold Products By The Date (0) | 2024.04.06 |
[LeetCode] 626. Exchange Seats (0) | 2024.04.05 |
[LeetCode] - 601. Human Traffic Of Stadium (0) | 2024.04.05 |