Search code examples
sqlsql-serverwindow-functionscross-joinhana-sql-script

Generate data combinations in sql


I have a table like below -

COL1 COL2
101 A
102 B
102 C
102 D
103 C
103 E

I need to generate all possible combinations along with uniqueID for a set of unique values in COL1 shown as below - There are 3 unique values in COL1, 6 combinations are possible and so 18 rows should be in the result.

1,101,A
1,102,B
1,103,C
2,101,A
2,102,B
2,103,E
3,101,A
3,102,C
3,103,C
4,101,A
4,102,C
4,103,E
5,101,A
5,102,D
5,103,C
6,101,A
6,102,D
6,103,E

Please help and suggest an answer. I tried using LAG,LEAD, CROSS JOIN, unable to get to a solution.

Answer can be using any of HANA SQL Script or Oracle SQL or MS-SQL. I have a solution that works for fixed number of unique values in COL1, however I need the solution to be dynamic and should work with any number of combinations and values.


Solution

  • This answers the original version of the question.

    If I understand correctly, I think the simplest method is to put the values on a single row:

    select row_number() over (order by t1.col1, t2.col1, t3.col1),
           t1.col1, t1.col2,
           t2.col1, t2.col2,
           t3.col1, t3.col2
    from t t1 join
         t t2
         on t1.col1 < t2.col1 join
         t t3
         on t2.col1 < t3.col1;
    

    You can unpivot these results if you like.