Skip to content
Advertisement

Generate all combinations of values with set list of values for each character in SQL

I have a dataset that looks like this

Position Value
1 1
1 2
1 3
2 8
3 5
3 6

And I’d like to generate all combinations of strings with the value at each position.

For this example, the output would look like

Output
185
285
385
186
286
386

The order doesn’t particularly matter.

Note: There can be an arbitrary amount of groups and values per group.

The below SQL sets up the sample input.

Advertisement

Answer

You can use a recursive CTE for this, dynamic SQL is not needed

SQL Fiddle

If there are gaps then you a need a more complex solution:

SQL Fiddle

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