表:Queue
Column Name | Type |
---|---|
person_id | int |
person_name | varchar |
weight | int |
turn | int |
有一队乘客在等着上巴士。然而,巴士有1000 千克 的重量限制,所以其中一部分乘客可能无法上巴士。
编写解决方案找出 最后一个 上巴士且不超过重量限制的乘客,并报告 person_name 。
题目测试用例确保顺位第一的人可以上巴士且不会超重。
返回结果格式如下所示。
示例 1:
输入:
Queue 表
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 |
输出:
person_name |
---|
John Cena |
解释:
为了简化,Queue 表按 turn 列由小到大排序。
+------+----+-----------+--------+--------------+
| Turn | ID | Name | Weight | Total Weight |
+------+----+-----------+--------+--------------+
| 1 | 5 | Alice | 250 | 250 |
| 2 | 3 | Alex | 350 | 600 |
| 3 | 6 | John Cena | 400 | 1000 | (最后一个上巴士)
| 4 | 2 | Marie | 200 | 1200 | (无法上巴士)
| 5 | 4 | Bob | 175 | ___ |
| 6 | 1 | Winston | 500 | ___ |
+------+----+-----------+--------+--------------+
SELECT a.turn, a.person_name, a.weight, SUM(b.weight) AS weightSum
FROM Queue a, Queue b
WHERE a.turn >= b.turn
GROUP BY a.turn
ORDER BY a.turn
| turn | person_name | weight | weightSum |
| ---- | ----------- | ------ | --------- |
| 1 | Alice | 250 | 250 |
| 2 | Alex | 350 | 600 |
| 3 | John Cena | 400 | 1000 |
| 4 | Marie | 200 | 1200 |
| 5 | Bob | 175 | 1375 |
| 6 | Winston | 500 | 1875 |
取体重累积小于或等于 1000 的数据
SELECT a.turn, a.person_name, a.weight, SUM(b.weight) AS weightSum
FROM Queue a, Queue b
WHERE a.turn >= b.turn
GROUP BY a.turn
HAVING weightSum <= 1000
ORDER BY a.turn
| turn | person_name | weight | weightSum |
| ---- | ----------- | ------ | --------- |
| 1 | Alice | 250 | 250 |
| 2 | Alex | 350 | 600 |
| 3 | John Cena | 400 | 1000 |
之后排序改成倒序,取第一行数据即可
SELECT a.person_name
FROM Queue a, Queue b
WHERE a.turn >= b.turn
GROUP BY a.turn
HAVING SUM(b.weight) <= 1000
ORDER BY a.turn DESC
LIMIT 1
| person_name |
| ----------- |
| John Cena |