如何返回2列中所有值组合的列表,以便它们是T-SQL中的新行?
例如
Col1, Col2
---- ----
1 2
1 4
1 5
Run Code Online (Sandbox Code Playgroud)
并将其转换为所有组合:
1 2
1 4
1 5
2 4
2 5
4 5
Run Code Online (Sandbox Code Playgroud)
Bob*_*ack 36
您可以将笛卡尔连接到表中,这将返回两列的所有组合.
select
distinct
t1.Col1,
t2.Col2
from
MyTable t1,
MyTable t2
Run Code Online (Sandbox Code Playgroud)
Joe*_*lli 35
假设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
Run Code Online (Sandbox Code Playgroud)
你可以自我交叉加入......
SELECT a.Col1, b.Col2
FROM MyTable a
CROSS JOIN MyTable b
Run Code Online (Sandbox Code Playgroud)
小智 7
我正在寻找能够使用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;
Run Code Online (Sandbox Code Playgroud)