# Select one value from each row where the SUM of all selected values equals known number X

I have a known number, x and several named columns (ix, col1, col2, col3...) and need to select a single value from either col1, col2, or col3 from each row (not necessarily the same column) where the total adds up to the known number x. I am having a difficult time trying to figure out the logic for this.

There is no chance of multiple result sets using the numbers in the columns, but one column from each row MUST be returned, with all columns returned adding up to the number X.

Ideally it would be something like this:

SELECT * as results FROM table WHERE sum(results) = number

however I can't use * in the sum statement, and it is possible that more than one result from each column (although being in separate rows) could be returned. SO I can't do Select col1, col2 col3 etc. As well, the table has a primary key IX and 64 columns, so any select case statement, or such won't work

• – mustaccio Jul 6 at 15:15
• Yes, the backpack problem is quite similar, however it involves reiterating through all possible combinations of results, which in a list of thouands of rows is completely inadequate. I am hoping to find a solution in either sql, or if needed an algorithm in code (as the initial table is created in code then output to the database for calculation). – Sunsing Jul 6 at 15:52

## 1 Answer

May be it will help you

``````SELECT * as results FROM table HAVING sum(col1) = number OR sum(col2) = number OR sum(col3) = number
``````

Thanks.