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

smdncfj3  于 2022-11-21  发布在  其他
关注(0)|答案(8)|浏览(182)

如何返回两列中所有值组合的列表,使它们成为T-SQL中的新行?
例如:

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

把它转化成所有的组合

ax6ht2ek

ax6ht2ek1#

您可以将表与其自身进行笛卡尔联接,这将返回两列的所有组合。

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

qcbq4gxm2#

假设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
p5fdfcr1

p5fdfcr13#

您可以执行自我交叉链接...

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

sh7euo9m4#

我一直在寻找只使用Microsoft Access 2016可用的SQL来实现这一点的代码。我最终找到了一些其他人可能会发现有用的东西。此代码使用了交叉连接,因此我发现有必要将两列拆分为两个单独的表(每个列有一列)。AND语句强制一列小于另一列,从而消除任何重复的1-2、2-1排序。

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

jbose2ul5#

我觉得这太复杂了!

SELECT distinct Col1, Col2
FROM MyTable

以获取所有可能的组合..

izj3ouym

izj3ouym6#

这使用了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
xzv2uavs

xzv2uavs7#

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

;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
kd3sttzy

kd3sttzy8#

让Joe回答起来更轻松

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

相关问题