2012-09-19 67 views
1

我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

回答

5

打完记录数,只需调理的加盟,使该左边总是等于或者小于!

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

大声笑..我想确切的事情,但你排除,我= j的... –

+0

修正,只是您的评论之前:) – RichardTheKiwi

+0

是啊..现在都好:)))..尼斯工作。 –