Return all possible combinations of values on columns in SQL

后端 未结 8 2453
轮回少年
轮回少年 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:15

    I think this has been over complicated! Just:

    SELECT distinct Col1, Col2
    FROM MyTable
    

    to get all possible combinations..

    0 讨论(0)
  • 2020-11-28 11:16

    This uses 2 cte's, the first simply reproduces your input table, the second turns both columns into a single column. The final select crossjoin's this set to itself to produce the required output

    with t(c1,c2)
    AS
    (
        select 1,2
        union select 1,4
        union select 1,5
    )
    ,t2(c)
    as
    (
        select c1 from t
        union select c2 from t
    )
    select t2_1.c, t2_2.c
    from t2 t2_1 
    cross join t2 t2_2
    where t2_1.c<t2_2.c
    order by t2_1.c
    
    0 讨论(0)
提交回复
热议问题