Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rows having sum equal to given value

Tags:

sql

sql-server

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.

like image 901
Humdum Avatar asked Jun 09 '11 07:06

Humdum


People also ask

How do I select rows that sum up to a specific value in SQL?

This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause. The AVG function finds the arithmetic mean for a group of records in a SQL table.

How do I sum rows with the same ID?

To sum rows with same ID, use the GROUP BY HAVING clause.

Can we use SUM function in having clause?

You can use it to add all the values in one column across all rows in a table, to total the results of an expression that uses more than one column, and to sum up values for a group of rows. You can also use SUM() inside the HAVING clause to filter data according to the summed values.

How do you add value to a row?

If you want to add data to your SQL table, then you can use the INSERT statement. Here is the basic syntax for adding rows to your SQL table: INSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc); The second line of code is where you will add the values for the rows.


1 Answers

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.

like image 156
Martin B Avatar answered Nov 09 '22 22:11

Martin B