如何在sql中的两列中查找所有匹配的行?

dfuffjeb  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(216)

我的表有两列包含代码对(parentcodes和childcodes)。它们是唯一的配对,但每个代码可以而且经常在每列中重复。我试图从另一列中提取每个代码的每个示例以及所有相关值的列表。
所以基本上

Select ParentCode, Childcode 
from TABLE 
where count(ParentCode)>1

(反之亦然)
如果我想在select中同时包含这两个列,似乎必须在group by中包含这两个列。我试过子查询,但没有成功。我知道我可以在vba中设置一个脚本来循环每个代码并返回结果(运行一个基本的 select where count > 1 ),但这似乎是效率最低的方法。
样本数据:

5kgi1eie

5kgi1eie1#

要获取作为父代码或子代码也重复了一次以上,您可以在中使用:

select Parentcode, Childcode
from Table
where Parentcode in (
    select Parentcode
    from Table
    group by Parentcode
    having count(Parentcode) > 1
)
or Childcode in (
    select Childcode
    from Table
    group by Childcode
    having count(Childcode) > 1
)
v8wbuo2f

v8wbuo2f2#

你应该马上就到。

select Perentcode, count(ParentCode) count 
from TABLE 
group by ParentCode 
having count(Parentcode)>1
hgqdbh6s

hgqdbh6s3#

您可以使用exists:

select t.* from tablename t
where
  exists (select 1 from tablename where parentcode <> t.parentcode and childcode = t.childcode)
  or
  exists (select 1 from tablename where parentcode = t.parentcode and childcode <> t.childcode)

相关问题