我尝试从同一个表中的每个元素中提取表中每个元素的所有对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,i
是n*(n+1)/2
后的记录数
答案 0 :(得分:6)
所以,只需调整连接,使左侧始终等于或小于!
select a.Id L,b.id R
into #cross
from MyTable a
inner join mytable b on a.id <= b.id