Skip to content
Advertisement

Using SQL to select all possible set of rows using value of a column

I’m wondering if such thing is possible with SQL only. What I’m trying to achieve here is the following:

An SQL table with the following column:

I want to select all possible set of rows satisfying the sum of DURATION from each row being lesser than or greater than a given value. For example if the value is 20 then the result of lesser than 20 should contain 3 sets of rows

14 + 5

5 + 3

14 + 3

Advertisement

Answer

Here’s a recursive CTE solution (requiring MySQL 8.0+) for finding all combinations of sums of rows that add up to less than a given value. If you don’t have MySQL 8, you will probably need to write a stored procedure to do the same looping.

Sample output for my demo on dbfiddle:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement