Return all possible combinations of values on columns in SQL

后端 未结 8 2457
轮回少年
轮回少年 2020-11-28 10:44

How do I return a list of all combinations of values in 2 columns so they are new rows in T-SQL?

e.g.

Col1, Col2
----  ----
1     2
1     4
1     5
<         


        
8条回答
  •  抹茶落季
    2020-11-28 10:59

    I was looking for something that would do this using only the SQL available to Microsoft Access 2016. I ended up figuring out something that others may find useful. This code utilizes CROSS JOIN so I found that it is necessary to split the two columns into two separate tables (each with one column). The AND statement forces one column to be less than the other, thereby eliminating any repetitive 1-2, 2-1 sort of occurrences.

    SELECT DISTINCT Table1.Column1, Table2.Column1
    FROM Table1, Table2
    WHERE Table1.Column1 <> Table2.Column1
    AND Table2.Column1 < Table1.Column1;
    

提交回复
热议问题