Return all possible combinations of values on columns in SQL

后端 未结 8 2456
轮回少年
轮回少年 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 11:02

    Assuming at least SQL 2005 for the CTE:

    ;with cteAllColumns as (
        select col1 as col
            from YourTable
        union
        select col2 as col
            from YourTable
    )
    select c1.col, c2.col 
        from cteAllColumns c1 
            cross join cteAllColumns c2 
        where c1.col < c2.col
        order by c1.col, c2.col
    

提交回复
热议问题