Reputation: 19037
I have 30 records in a table having column "box number" and "weight". I have to find 20 boxes out of 30 boxes whose sum of weight is nearest to 1000 kg.
Upvotes: 3
Views: 1753
Reputation: 1269773
The way you would solve this in SQL is not recommended, and may not even be feasible on any machine. But, you can express the brute force solution as:
select box1.id, box2.id, . . . ,
(box1.weight + box2.weight + . . .)
from box box1 join
box box2
on box2.id > box1.id join
box box3
on box3.id > box2.id join
box box4
on box4.id > box3.id
. . .
box box20
on box20.id > box19.id
order by abs(1000 - (box1.weight + box2.weight + . . .))
The "on" conditions guarantee that you are looking at each set of boxes once, ordered by their unique ids. The use of "join" rather than "left join" ensures that you end up with exactly 20 boxes.
Upvotes: 0
Reputation: 8280
SQL Server:
select TOP 20 box_number
from t_boxes
group by box_number
order by ABS(SUM(box_weight) - 1000) ASC
Edit: In case I misunderstood your question and you actually want to solve knapsack problem. This is something that you really should do in SQL, but you can read this article with very appropriate name: And now for a completely inappropriate use of SQL Server.
Upvotes: 2