2017-07-06 16 views
3

我有兩列數據集:T-SQL查詢對,其中至少有一名成員有兩對以上的不同成員

source   target 
Michael Scott Kelly Kapoor 
Jim Halpert  Pam Beasley 
Jim Halpert  Pam Beasley 
Dwight Schrute Angela 
Angela   Dwight Schrute 
Erin   Meredith 
Erin   Meredith 
Kevin Malone Stanley Hudson 
Kevin Malone Ryan Howard 
Pam Beasley  Oscar 

我想找到,其中包括誰擁有至少一個成員的行多對與至少兩個不同的成員。所以,最終的結果應該返回:

source   target   
Jim Halpert  Pam Beasley 
Jim Halpert  Pam Beasley 
Kevin Malone Stanley Hudson 
Kevin Malone Ryan Howard 
Pam Beasley  Oscar 

Michael --> Kelly被刪除,因爲無論有什麼其他環節 Dwight Schrute --> AngelaAngela --> Dwight Schrute是因爲拆除,雖然有多個鏈接,鏈接是相同的成員之間。 Erin --> MeredithErin --> Meredith被刪除,因爲同樣的成員之間的鏈接(儘管在相同的方向)。

我知道如何找到涉及相同成員在任一方向不同的鏈接:

select source 
     ,target 
from dbo.networktest 
group by source, target 
having count(*) > 1 
union 
select b.source 
     ,b.target 
from dbo.networktest a 
left outer join dbo.networktest b on a.source = b.target and a.target = b.source 
where b.source is not null and b.target is not null 

我將如何改變(或報廢/重建),要實現我的目標是什麼?謝謝你們所有人的洞察!如果我能讓我的問題更清楚,請告訴我。

回答

3

我覺得exists確實WHA T優想:

select nt.* 
from networktest nt 
where exists (select 1 
       from networktest nt2 
       where nt2.source in (nt.source, nt.target) and 
        nt2.target not in (nt.source, nt.target) 
      ) or 
     exists (select 1 
       from networktest nt2 
       where nt2.target in (nt.source, nt.target) and 
        nt2.source not in (nt.source, nt.target) 
      ); 
+0

哇。完美地工作 - 對於簡單的問題抱歉!當我允許時,我會接受答案。 –