对称交叉连接

Fel*_*ano 1 sql t-sql sql-server

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

select a.Id L,b.id R into #cross from MyTable a cross join mytable b 
Run Code Online (Sandbox Code Playgroud)

我处于这样的情况,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)
Run Code Online (Sandbox Code Playgroud)

但我插入时无法查询目标表,如SQL Server所述:

The SELECT INTO statement cannot have same source and destination tables
Run Code Online (Sandbox Code Playgroud)

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

编辑 仅供参考,我说:"我需要一半的记录",这是错误的记录数以帐户之后i,j == j,in*(n+1)/2

Ric*_*iwi 6

所以,只需调整连接,使左侧总是等于或小于!

    select a.Id L,b.id R
      into #cross
      from MyTable a
inner join mytable b on a.id <= b.id
Run Code Online (Sandbox Code Playgroud)