返回SQL中列的所有可能值组合

时间:2010-12-07 16:01:05

标签: sql-server tsql

如何返回2列中所有值组合的列表,以便它们是T-SQL中的新行?

e.g。

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

并将其转换为所有组合:

1     2
1     4
1     5
2     4
2     5
4     5

8 个答案:

答案 0 :(得分:36)

你可以将笛卡儿加入表中,这将返回两列的所有组合。

select 
    distinct
    t1.Col1,
    t2.Col2
from 
    MyTable t1,
    MyTable t2

答案 1 :(得分:33)

至少假设CTE的SQL 2005:

;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

答案 2 :(得分:9)

你可以自我交叉加入...

SELECT a.Col1, b.Col2
FROM MyTable a
CROSS JOIN MyTable b

答案 3 :(得分:5)

我一直在寻找能够使用Microsoft Access 2016可用的SQL来实现这一目标的东西。我最终找出了其他人可能觉得有用的东西。此代码使用CROSS JOIN,因此我发现有必要将两列分成两个单独的表(每个表有一列)。 AND语句强制一列小于另一列,从而消除任何重复的1-2,2-1次出现。

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

答案 4 :(得分:4)

我认为这已经过于复杂了!

只需:

SELECT distinct Col1, Col2

FROM MyTable

获得所有可能的组合..

答案 5 :(得分:1)

这使用2个cte,第一个只是重现你的输入表,第二个将两列变成一个列。最终的选择交叉连接将其设置为自身以产生所需的输出

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

答案 6 :(得分:0)

我发现内部联接更直观,因为我比交叉联接更频繁地使用它:

;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

答案 7 :(得分:0)

让乔更容易回答

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

验证你的组合数量(行数) http://www.calculatorsoup.com/calculators/discretemathematics/combinations.php