1204. Last Person to Fit in the Bus
https://leetcode.com/problems/last-person-to-fit-in-the-bus/
Last Person to Fit in the Bus - LeetCode
Can you solve this real interview question? Last Person to Fit in the Bus - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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 an SQL query 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 limit.
Example
Input:
Queue table:
+-----------+-------------+--------+------+
| person_id | person_name | weight | turn |
+-----------+-------------+--------+------+
| 5 | Alice | 250 | 1 |
| 4 | Bob | 175 | 5 |
| 3 | Alex | 350 | 2 |
| 6 | John Cena | 400 | 3 |
| 1 | Winston | 500 | 6 |
| 2 | Marie | 200 | 4 |
+-----------+-------------+--------+------+
Output:
+-------------+
| person_name |
+-------------+
| John Cena |
+-------------+
답
# 1
SELECT * -- q1.person_name
FROM Queue q1 JOIN Queue q2 ON q1.turn >= q2.turn
GROUP BY q1.turn
HAVING SUM(q2.weight) <= 1000 -- 몸무게가 1000될때까지 더하기
ORDER BY SUM(q2.weight) DESC -- 몸무게 합(최소1000임) 내림차순
LIMIT 1 -- 마지막 승객만 출력
# 2
SELECT person_name
FROM
(SELECT person_name, weight, turn, sum(weight) over(order by turn) AS cum_sum
FROM queue) x
WHERE cum_sum <= 1000
ORDER BY turn DESC LIMIT 1;
'🛠️Skill > CodingTest' 카테고리의 다른 글
[leetcode] 1321. Restaurant Growth/7일간의 이동 평균 (0) | 2023.03.29 |
---|---|
[leetcode] 1341. Movie Rating / 평점 가장 많이 남긴 사람, 평점이 가장 높은 영화 (0) | 2023.03.27 |
[leetcode] 1174. Immediate Food Delivery II / 즉시배송할 수 있는 주문비율 (0) | 2023.03.08 |
[leetcode] 550. Game Play Analysis IV/ 이틀 연속 로그인한 유저 /LEFT JOIN/IN (0) | 2023.02.19 |
[leetcode] 1164. Product Price at a Given Date / 지정 날짜에 변경된 데이터 조회 / UNION (0) | 2023.02.17 |
댓글