【问题标题】:Find group of records that match multiple values查找匹配多个值的记录组
【发布时间】:2015-12-18 18:31:41
【问题描述】:

我有以下数据:

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)

我查看了this question,它非常相似,但 OP 会查找不包含单个值的组。

非常感谢任何帮助!

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您可以使用条件聚合来做到这一点:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2011-10-19
      • 2015-08-02
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多