Skip to content
Advertisement

SQL – find all combinations

From a dataset like this, I need to get all possible combinations of cases in the same room so that no case overlaps another.

The expected result is

I am able to get single line results of what case can be combined with which other case like:

And I’ve tried some recursions but I am at a loss nowhere near to getting the type of results I need, I would appreciate any guidance anyone can share.

Advertisement

Answer

Here is one method using a string aggregation. To get the overlaps by time:

You can then use this as a subquery/CTE to enumerate the combinations:

EDIT:

In earlier versions of SQL Server, you can use the XML method for string aggregation:

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