People LeetCode-1204. The last to enter the elevator (middle) from the link

Table: Queue

+ ------------- + --------- +
| Column the Name | Type |
+ ------------- + ---- + -----
| person_id | int |
| PERSON_NAME | VARCHAR |
| weight | int |
| Turn | int |
+ ------------- + --------- +
the person_id is the primary key of this table.
The table shows all the people waiting for the elevator information.
Person_id turn table and the columns contain all numbers from 1 to n, where n is the number of rows in the table.
 

Elevator maximum load of 1000.

Write a SQL query to find the last one to enter the elevator and does not exceed the weight limit of person_name. Topic ensure that the queue first person to enter the elevator.

Results are as follows:

Queue 表
+-----------+-------------------+--------+------+
| 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 表
+-------------------+
| person_name       |
+-------------------+
| Thomas Jefferson  |
+-------------------+

To simplify, Queue trun table are sorted in ascending column.
In the embodiment George Washington (id 5), John Adams (id 3) and Thomas Jefferson (id 6) will be able to enter the elevator, and because their weight is 250 + 350 + 400 = 1000.
Thomas Jefferson (id 6) and is the last person to enter the appropriate weight of the elevator.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/last-person-to-fit-in-the-elevator
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Moderation: Discover the last sum weighing no more than 1000 names of people.

Thoughts: sum judge just 1,000 people (less than 1000).

Problem solving:

select person_name
from Queue q1
-- 如果q1到第三行,子查询的turn也只是将前三行的体重相加,
where (select sum(weight) from Queue where turn <= q1.turn) <= 1000
-- 然后将turn降序,选择第一个就是最后一个人。
order by turn desc limit 1

Method Two:

Since the link with a.turn> = b.turn screened as part of his accumulated, and finally select a person in the elevator is determined by sorting the weight of the final sum

select a.person_name
from queue a, queue b
where a.turn >= b.turn
group by a.person_id
having sum(b.weight) <= 1000
order by a.turn desc
limit 1

 Knowledge points:

Self-join

Published 144 original articles · won praise 2 · Views 5748

Guess you like

Origin blog.csdn.net/Hello_JavaScript/article/details/104698584
Recommended