我正在尝试在SQL Server 2012或更高版本中开发T-SQL,这样我就可以在一个组中找到两列记录的所有组合。
鉴于以下数据:
Col1 Col2
3 2
3 5
3 6
7 1
7 9
。 。
。 。
。 。更多群体
如何获得如下所需的结果:
Col1 Col2
2 2
2 3
2 5
2 6
3 3
3 2
3 5
3 6
5 5
5 2
5 3
5 6
6 6
6 2
6 3
6 5
1 1
1 7
1 9
7 7
7 1
7 9
9 1
9 7
9 9
答案 0 :(得分:0)
我很确定有更好的方法:
create table #temp
(
col1 INT,
col2 INT
);
INSERT INTO #temp VALUES (3,2),(3,5),(3,6),(7,1),(7,9)
SELECT a.col1, b.col1
FROM (
select col1, dense_rank() over (order by col1) dr from #temp
UNION
select col2, dense_rank() over (order by col1) dr from #temp
) a
JOIN (
select col1, dense_rank() over (order by col1) dr from #temp
UNION
select col2, dense_rank() over (order by col1) dr from #temp
) b
ON a.dr = b.dr
答案 1 :(得分:0)
怎么样?
应该可以一步到位地使用SQL ...