i have table of packages. each packages has priority , weight:
priority | weight ----------------- 1 4 2 3 3 5 4 1 5 3
i want fit packages, sorted priority, box, until maximum allowed weight of box reached. example, if have box of maximum allowed weight 10, pick following 2 packages:
priority | weight ----------------- 1 4 2 3
in sql words, want keep select * package order priority
long sum(weight) <= 10
.
is possible in postgresql 9.x?
you can use window function sum
order by
clause calculate cumulative sum of weight in order of priority , filter on that.
select priority, weight ( select t.*, sum(weight) on ( order priority ) cuml_weight your_table t ) t cuml_weight <= 10;
demo
as asked op, can done using correlated subquery:
select * ( select t.*, ( select sum(weight) your_table t2 t2.priority <= t.priority ) cuml_weight your_table t ) t cuml_weight <= 10;
Comments
Post a Comment