sql - T-SQL 查找至少一个成员与不同成员有两个或更多对的对

标签 sql sql-server tsql

我有一个包含两列的数据集:

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

我将如何更改(或废弃/重建)它以实现我的目标?感谢您提供任何见解!如果我能让我的问题更清楚,请告诉我。

最佳答案

我认为 exists 做你想做的事:

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)
             );

关于sql - T-SQL 查找至少一个成员与不同成员有两个或更多对的对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44955518/

相关文章:

sql-server - 在不删除sql server中的表的情况下无法添加列

mysql - 带有表变量和返回值输出的动态 SQL

sqlite3查询磁盘空间使用情况

sql - 同时在同一个表中插入和选择

mysql - 合并多行并计入另一个表中的新列

sql - 将记录的每一列转换为单独的记录

等同于SQL Server OFFSET

sql-server-2008 - 使用顺序整数更新表

sql - 具有通用数据的新记录

sql - 在SQL Server中创建枚举