2017-08-21 152 views
1

我具有其中弧(由起始[S]和終止[E]的)的曲線圖的形式存儲在一個關係表如下的圖形數據的圖形數據循環:刪除重複/從

IF OBJECT_ID('tempdb..#Test') IS NOT NULL DROP TABLE #Test; 

CREATE TABLE #Test 
(
    S NVARCHAR(1) 
    ,E NVARCHAR(1) 
); 

insert into #Test (S, E) values ('a', 'b'); 
insert into #Test (S, E) values ('b', 'a'); 
insert into #Test (S, E) values ('a', 'c'); 

所以該圖由這些弧的:

a -> b 
b -> a 
a -> c 

我想刪除重複/循環:一個 - > b和b - >一個=>甲 - >乙。這可能嗎?

+0

你想插入後刪除或只插入一個這樣的對到桌上? –

+0

無論哪種方式都很好。讓我們說#Test是一個臨時表,非循環/重複數據寫入#Test1。 – cs0815

+0

@ shA.t這不重複! – cs0815

回答

3

;with cte as (
    Select * 
      ,RN = Row_Number() over (Partition By case when S<E then S+E else E+S end order by s,e) 
    From #Test 
) 
Delete From cte Where RN>1 

更新的測試

S E 
a b 
a c 
+0

看起來很有趣... – cs0815

+0

@csetzkorn唯一的技巧是通過案例創建標準化的對。然後Row_Number()將處理重複對 –

+0

作爲s和e是字符可以S cs0815

0

如果你只得到了簡單的重複就像你的例子:

DELETE 
FROM #test AS t1 
WHERE EXISTS 
(SELECT * 
    FROM #test AS t2 
    WHERE t1.S = t2.E -- there's the same S/E combination, but switched 
    AND t1.E = t2.S 
    AND t1.S > t2.S -- delete only one of the combinations 
)