SQL - select 行直到聚合匹配

SQL - select rows until aggregate is matched

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

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

这在 Postgre 中可能吗SQL 9.x?

您可以使用 window 函数 sumorder 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;

Demo

正如 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;

Demo