0

我有一张包裹表。每个包裹都有一个优先级和重量:

priority | weight
-----------------
1         4
2         3
3         5
4         1
5         3

我想将所有按优先级排序的包裹放入一个盒子中,直到达到盒子的最大允许重量。例如,如果我有一个最大允许重量为 10 的盒子,我会选择以下两个包裹:

priority | weight
-----------------
1         4
2         3

用 SQL 的话来说,我想select * from package order by priority保持sum(weight) <= 10.

这在 PostgreSQL 9.x 中可行吗?

4

1 回答 1

1

您可以使用sum带有order by子句的窗口函数按优先级顺序计算权重的累积总和并对其进行过滤。

select priority, weight
from (
    select t.*,
        sum(weight) over (
            order by priority
            ) as cuml_weight
    from your_table t
    ) t
where cuml_weight <= 10;

演示

正如 OP 所要求的,这也可以使用相关子查询来完成:

select *
from (
    select t.*,
        (
            select sum(weight)
            from your_table t2
            where t2.priority <= t.priority
            ) as cuml_weight
    from your_table t
    ) t
where cuml_weight <= 10;

演示

于 2017-04-05T18:06:01.480 回答