Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

sql - How to get rows having sum equal to given value

There is table contain

ID     Qty
----------
1       2
2       4
3       1
4       5

Now if i had to choose rows where sum of Qty equals to 10, How can i do this ?

like 2+4+1 = 7 but if i add 5 then 12

so ignore 2, then 4+1+5 = 10

How can i achieve this ?

Edit:

I want any possible combination which sums up to gives value. suppose 7 then any rows which sums up to 7 like wise if 8 then any rows sums up to 8

want row/rows having combination equals to given value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem you want to solve is called the subset sum problem. Unfortunately, it is NP-complete.

This means that, whether you use SQL or any other language to solve it, you will only be able to solve very small instances of the problem, i.e. ones with only a few entries in the table. Otherwise, the runtime will become excessive, since it grows exponentially with the number of rows in the table. The reason for this is that there is essentially no better way of finding the solution than to try all possible combinations.

If an approximate solution is acceptable, there is a polynomial time algorithm, which is described on the Wikipedia page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...