3

我正在尝试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

4

1 回答 1

7

因此,只需设置连接条件,使左侧始终等于或小于!

    select a.Id L,b.id R
      into #cross
      from MyTable a
inner join mytable b on a.id <= b.id
于 2012-09-19T07:31:45.080 回答