如何在SQL中查找两列中的所有匹配行?
我的表有两列,其中包含代码对Parentcodes和Childcodes。它们是唯一的配对,但每个代码可以而且经常在每列中重复。我试图从另一列中提取每个代码的每个实例以及所有相关值的列表 所以基本上如何在SQL中查找两列中的所有匹配行?,sql,sql-server,Sql,Sql Server,我的表有两列,其中包含代码对Parentcodes和Childcodes。它们是唯一的配对,但每个代码可以而且经常在每列中重复。我试图从另一列中提取每个代码的每个实例以及所有相关值的列表 所以基本上 Select ParentCode, Childcode from TABLE where count(ParentCode)>1 反之亦然 如果我想在select中同时包含这两个列,那么我必须在group by中包含这两个列。我尝试过子查询,但没有成功。我知道我可以在VBA中设置一个脚
Select ParentCode, Childcode
from TABLE
where count(ParentCode)>1
反之亦然
如果我想在select中同时包含这两个列,那么我必须在group by中包含这两个列。我尝试过子查询,但没有成功。我知道我可以在VBA中设置一个脚本,循环遍历每个代码,并返回运行基本select的结果,其中count>1,但这似乎是效率最低的方法
样本数据:
你应该就在那里
select Perentcode, count(ParentCode) count
from TABLE
group by ParentCode
having count(Parentcode)>1
要获取作为父代码或子代码也重复了一次以上,您可以在中使用:
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
)
您可以使用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)
这里有一个提示-您将希望使用COUNT与GROUP BY和HAVING。感谢您的提示-我尝试过,但似乎无法使其工作。看起来GroupBy需要两列,所以我得到0个结果,因为它们都是unqiue对。下面是代码:选择Childcode,按Childcode从表组中选择ParentCode,ParentCode的countChildcode>1。。。。如果我漏掉任何一列,就会得到一个错误。再次感谢。很难从你的问题中猜出你想要什么。您能从表中包含一些示例行和所需结果的示例吗?请回答您的问题。请用您正在运行的数据库标记您的问题:mysql、oracle、postgresql…?谢谢!非常感谢您的时间和帮助!真的很感激它-将玩这个建议,以及-我不知道存在,但可以肯定地使用它在这个项目的其他领域!谢谢,给了我我想要的东西——更多的测试,但这看起来很棒,非常感谢。