Sum subset query

时间:2018-08-04 15:20:22

标签: mysql sql sum subset

CREATE TABLE Test (id integer, name varchar(100), weight integer, turn integer);
INSERT INTO Test (id, name, weight, turn) VALUES (5, "George Washington", 250, 1);
INSERT INTO Test (id, name, weight, turn) VALUES (4, "Thomas Jefferson", 175, 5);
INSERT INTO Test (id, name, weight, turn) VALUES (3, "John Adams", 350, 2);
INSERT INTO Test (id, name, weight, turn) VALUES (6, "Thomas Jefferson", 400, 3);
INSERT INTO Test (id, name, weight, turn) VALUES (1, "James Elephant", 500, 6);
INSERT INTO Test (id, name, weight, turn) VALUES (2, "Will Johnliams", 200, 4);

The query should return a table containing exactly one record 'Thomas Jefferson' as the first three people will fit (in the order : George Washingthon, John Adams, Thomas Jefferson). The sum of their weight is 250+350+400

The problem is I have to query where person will fit in elevator that can hold max <= 1000. how can I solve this problem?

1 个答案:

答案 0 :(得分:3)

我们可以在此处使用相关子查询来检查按转弯顺序给出的人员的总跑步重量:

SELECT t1.*
FROM Test t1
WHERE (SELECT SUM(t2.weight) FROM Test t2 WHERE t2.turn <= t1.turn) <= 1000
ORDER BY t1.turn DESC
LIMIT 1;

注意:如果您希望所有符合条件的人都在体重限制范围内,则只需从上述查询中删除LIMIT子句即可。

相关问题