Leetcode - 1204. Last Person to Fit in the Elevator

该SQL查询旨在找到最后一个能在不超载电梯(最大承重1000)的情况下进入的人。通过自我连接Queue表并按顺序计算累计体重,然后筛选出累计重量不超过限制的批次,最后按顺序降序排列并取第一个结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Table: Queue

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| person_id   | int     |
| person_name | varchar |
| weight      | int     |
| turn        | int     |
+-------------+---------+
person_id is the primary key column for this table.
This table has the information about all people waiting for an elevator.
The person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table.

 

The maximum weight the elevator can hold is 1000.

Write an SQL query to find the person_name of the last person who will fit in the elevator without exceeding the weight limit. It is guaranteed that the person who is first in the queue can fit in the elevator.

The query result format is in the following example:

Queue table
+-----------+-------------------+--------+------+
| person_id | person_name       | weight | turn |
+-----------+-------------------+--------+------+
| 5         | George Washington | 250    | 1    |
| 3         | John Adams        | 350    | 2    |
| 6         | Thomas Jefferson  | 400    | 3    |
| 2         | Will Johnliams    | 200    | 4    |
| 4         | Thomas Jefferson  | 175    | 5    |
| 1         | James Elephant    | 500    | 6    |
+-----------+-------------------+--------+------+

Result table
+-------------------+
| person_name       |
+-------------------+
| Thomas Jefferson  |
+-------------------+

Queue table is ordered by turn in the example for simplicity.
In the example George Washington(id 5), John Adams(id 3) and Thomas Jefferson(id 6) will enter the elevator as their weight sum is 250 + 350 + 400 = 1000.
Thomas Jefferson(id 6) is the last person to fit in the elevator because he has the last turn in these three people.


要知道哪一位最后fit elevator,则需要知道之前进去的人的体重总和,即每进去一个人计算电梯里人的体重总和。也就是说,Queue table需要添加一列weight_accumulate. 可以用self join turn来实现:

from Queue q1 inner join Queue q2 on q1.turn >= q2.turn

得到table如下:

weight1turn1weight2turn2
25012501
35022501
35023502
40032501
40033502
40034003
20042501
20043502
20044003
20042004
17552501
17553502
17554003
17552004
17551755
50062501
50063502
50064003
50062004
50061755
50065006

 

group by q1.turn,算出q2.weight的总和即每进去一位的体重总和。

coding:

select q1.person_name as person_name
from Queue q1 inner join Queue q2
on q1.turn >= q2.turn
group by q1.turn
having sum(q2.weight) <= 1000
order by q1.turn desc
limit 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值