SQL - 选择行直到聚合匹配

时间:2017-04-05 18:01:35

标签: sql postgresql aggregate-functions aggregates

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

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中是否可行?

1 个答案:

答案 0 :(得分: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;

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