查找匹配多个值的记录组

4
我有以下数据:
ID --- ParentID --- DataValue  
1  ---    1     ---    1  
2  ---    1     ---    2  
3  ---    1     ---    6  
4  ---    2     ---    1  
5  ---    2     ---    2  
6  ---    2     ---    4  
7  ---    3     ---    1  
8  ---    3     ---    3  
9  ---    3     ---    5

针对每组记录(按ParentID分组),我想找到所有与DataValue中给定的所有值匹配的组,例如:

  • 对于值(1,2),将返回ParentID为1和2的组
  • 对于值(1,6),只返回ParentID为1的组(ParentID为2的组不包含6)

我看了这个问题,它非常相似,但OP寻找不包含单个值的组。

非常感谢您的帮助!

1个回答

4
您可以使用条件聚合来实现此操作:
select parentid 
from tablename
group by parentid
having sum(case when datavalue = 1 then 1 else 0 end) > 0 and
       sum(case when datavalue = 6 then 1 else 0 end) > 0

另一种方法是使用exists
select distinct parentid
from tablename t1
where exists(select * from tablename where parentid = t1.parentid and datavalue = 1) and
      exists(select * from tablename where parentid = t1.parentid and datavalue = 6)

另一种方法是计算不同的出现次数:
select parentid 
from tablename
where datavalue in(1, 6)
group by parentid
having count(distinct datavalue) = 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接