如何编写SQL查询以获得以下结果

时间:2020-03-16 10:02:44

标签: sql sql-server

我正在编写一个SQL查询以从表中获取结果。

这是一个实际的问题:在我的数据库中,有一个名为Contact的表。 该表中有两列Calling_PersonCalled_Person

假定该表包含以下数据:

表格:Contact

Calling_Person      Called_Person
--------------------------------------
AB                CD
CD                AB
AB                EF
EF                AB
AB                PQ
PQ                XY
XY                UV
XY                ZW
UV                XY

从上表中,我们只需要互相打电话的人。

预期输出:

Calling_Person      Called_Person
--------------------------------------
AB                 CD
AB                 EF
XY                 UV

在上表中,

  • AB和CD互相呼唤
  • AB和EF相互呼唤
  • XY和UV相互调用

我写了以下查询,但结果如下:

select * 
from test
where id2 in (select id1 from test as t
              where id2 in (select id1 from test where id1 = t.id2)
             )

结果:

Calling_Person      Called_Person
--------------------------------------
AB          CD
CD          AB
AB          EF
EF          AB
XY          UV
UV          XY

2 个答案:

答案 0 :(得分:1)

我猜您正在尝试将相同的对(例如(a,b)(b,a))组合在一起。您需要使用条件id1 < id2将其中一行标记为“主”行,并检查是否存在匹配项:

SELECT *
FROM t AS t1
WHERE id1 < id2 AND EXISTS (
    SELECT 1
    FROM t AS t2
    WHERE t2.id1 = t1.id2 AND t2.id2 = t1.id1
)

答案 1 :(得分:0)

如果您有所有配对,则只需使用:

select t.*
from t 
where id1 < id2;

如果您有一对,那么:

select t.*
from t 
where id1 < id2 or
      not exists (select 1
                  from t t2
                  where t2.id1 = t.id2 and t2.id2 = t.id1
                 );

如果您实际上有重复项,请使用select distinct

select distinct id1, id2
from t 
where id1 < id2 or
      not exists (select 1
                  from t t2
                  where t2.id1 = t.id2 and t2.id2 = t.id1
                 );