Table_1
D_ID Integer
Deposit_amt integerTable_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.
Just for fun I did a brute force solution. It will find combinations of one, two, or three records that add up to
Total_amt. You could expand it to handle more transactions per sum, by addingd4,d5subselects, etc.:Output:
Note: You could filter out individual rows whose
Deposit_amt > Total_amt, but this would probably not help performance much unlessDeposit_amtwas indexed.