In SQL find the combination of rows whose sum add up to a specific amount (or amt in other table)

Posted by SamH on Stack Overflow See other posts from Stack Overflow or by SamH
Published on 2010-02-13T00:05:35Z Indexed on 2010/03/22 7:21 UTC
Read the original article Hit count: 155

Filed under:

Table_1
D_ID Integer
Deposit_amt integer

Table_2
Total_ID
Total_amt integer

Is it possible to write a select statement to find all the rows in Table_1 whose Deposit_amt sum to the Total_amt in Table_2. There are multiple rows in both tables.

Say the first row in Table_2 has a Total_amt=100. I would want to know that in Table_1 the rows with D_ID 2, 6, 12 summed = 100, the rows D_ID 2, 3, 42 summed = 100, etc.

Help appreciated. Let me know if I need to clarify.

I am asking this question as someone as part of their job has a list of transactions and a list of totals, she needs to find the possible list of transactions that could have created the total. I agree this sounds dangerous as finding a combination of transactions that sums to a total does not guarantee that they created the total.

I wasn't aware it is an np-complete problem.

© Stack Overflow or respective owner

Related posts about sql