Skip to content
Advertisement

How to generate multiple combinations from tables using SQL?

I have few combinations of records in my table but i want to generate Multiple combinations from original table.

Records in table

codeset codevalue column system
test1 1 null sys1
test2 2 col2 sys1
test3 3 col3 sys1
test3 4 col4 sys1
test3 5 col5 sys1
test4 null col6 sys1
test5 6 col7 sys2
test5 7 col8 sys2

After applied below logic and would like to get expected output.

  • Group by ‘codeset’
  • system name should be ‘sys1’
  • ‘codevalue’ and ‘column’ should be more than 1 row
  • ‘codevalue’ and ‘column’ equal rows

Expected Output

codeset codevalue column system
test1 1 null sys1
test2 2 col2 sys1
test3 3 col3 sys1
test3 3 col4 sys1
test3 3 col5 sys1
test3 4 col3 sys1
test3 4 col4 sys1
test3 4 col5 sys1
test3 5 col3 sys1
test3 5 col4 sys1
test3 5 col5 sys1
test4 null col6 sys1
test5 6 col7 sys2
test5 7 col8 sys2

Advertisement

Answer

To get all possible combinations of codevalue and column for each codeset group when system has the value of sys1, you can use:

Or, as a hierarchical query:

Which, for the sample data:

Both output:

CODESET CODEVALUE COLUMN SYSTEM
test1 1 null sys1
test2 2 col2 sys1
test3 3 col3 sys1
test3 4 col3 sys1
test3 5 col3 sys1
test3 3 col4 sys1
test3 4 col4 sys1
test3 5 col4 sys1
test3 3 col5 sys1
test3 4 col5 sys1
test3 5 col5 sys1
test4 null col6 sys1
test5 6 col7 sys2
test5 7 col8 sys2

db<>fiddle here

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