Return all possible combinations of values on columns in SQL

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

    You could cartesian join the table to itself, which would return all combinations of both columns.

    select 
        distinct
        t1.Col1,
        t2.Col2
    from 
        MyTable t1,
        MyTable t2
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-28 11:02

    I find an inner join more intuitive because I use it more frequently than a cross join:

    ;with cteAllColumns as (
    select col1 as col
        from YourTable
    union
    select col2 as col
        from YourTable
    ) 
    
    select c1.col, c2.col 
    from cteAllColumns c1 
        join cteAllColumns c2 on 1=1
    where c1.col < c2.col
    order by c1.col, c2.col
    
    0 讨论(0)
  • 2020-11-28 11:07

    You can do a self cross join...

    SELECT a.Col1, b.Col2
    FROM MyTable a
    CROSS JOIN MyTable b
    
    0 讨论(0)
  • 2020-11-28 11:08

    Making Joe Answer easier

    declare @t1 table  (col1 varchar(5))
    insert @t1 
        select 'A' UNION
        select 'B' UNION
        select 'C' 
    
    
    declare @t2 table  (col2 varchar(5))
    insert @t2
        select '1' UNION
        select '2' UNION
        select '3' 
    
    
    ;with cteAllColumns as (
        select col1 as col
            from @t1
        union
        select col2 as col
            from @t2
    )
    select c1.col, c2.col 
        from cteAllColumns c1 
            cross join cteAllColumns c2 
        where c1.col < c2.col
        order by c1.col, c2.col
    

    verify your combinations Qty (No of rows) http://www.calculatorsoup.com/calculators/discretemathematics/combinations.php

    0 讨论(0)
提交回复
热议问题