对称交叉联接(Symmetric cross join)

2019-07-31 17:24发布

我tryng提取所有对说i,j ,从每个元素在表中对每个元素在同一个表,在这里我的查询:

select a.Id L,b.id R into #cross from MyTable a cross join mytable b 

我在那里的情况i,j == j,i所以需要只是一半的记录。 我天真的尝试是:

select a.Id L,b.id R into #cross from MyTable a cross join mytable b 
where not exists
    (select * from #cross c where c.L=R and c.R=L)

但我无法查询目标表,而在插入,如SQL Server的说:

The SELECT INTO statement cannot have same source and destination tables

我怎么能以有效的方式呢?

编辑仅供参考,我说:“我需要一半的记录”,这是错误的,在服用后账户记录计数i,j == j,in*(n+1)/2

Answer 1:

所以,只要调理加盟,使左侧总是等于或小!

    select a.Id L,b.id R
      into #cross
      from MyTable a
inner join mytable b on a.id <= b.id


文章来源: Symmetric cross join