【问题标题】:SQL - Finding rows with specific combination of values in a columnSQL - 在列中查找具有特定值组合的行
【发布时间】:2019-08-30 09:32:34
【问题描述】:

不知道如何准确地表达这个问题,最好用一个例子来理解。我试过在 SO 上环顾四周,但找不到我要找的东西。抱歉,如果存在的话,我很乐意关闭它。

使用 SQL 数据库,我的数据如下所示:

col1 | col2
------------
A    |   11
A    |   56
A    |   59
B    |   56
C    |   59
C    |   56

我想找到 col1 的值,在 col2 中,值是 56 和 59,但不是 11。所以对上面示例表的查询将只返回“C”。

我已经尝试过窗口化和子查询,如果感觉它不应该太难,但不是很成功。任何提示表示赞赏,谢谢!

【问题讨论】:

  • “56 和 59 但不是 11。”,你想要 A?我会说 C.
  • 如果 D 有 56、59 和 64 怎么办?应该退货吗?
  • @jarlh 你是对的,抱歉打错了,我的意思是'C'不知道为什么'A'出来了!我已经编辑了问题

标签: sql subquery window-functions


【解决方案1】:

为此我喜欢group byhaving

select col1
from t
group by col1
having sum(case when col2 = 56 then 1 else 0 end) > 0 and
       sum(case when col2 = 59 then 1 else 0 end) > 0 and
       sum(case when col2 = 11 then 1 else 0 end) = 0 ;

sum() 计算每个特定值。那么> 0 表示col1 值至少存在一行,= 0 表示不存在。

注意:这是基于您对问题的描述。这将返回'C',而不是'A',这与描述一致。

【讨论】:

    【解决方案2】:

    在执行GROUP BY 时,使用WHERE 子句仅包含这三个值。使用 HAVING 子句检查 56 是否为 min() 值,即不存在值 11。还要检查 59 是否是 max() 值,以确保 56 和 59 都存在。

    select col1
    from t
    where col2 in (11, 56, 59)
    group by col1
    having min(col2) = 56 and max(col2) = 59
    

    【讨论】:

      【解决方案3】:

      据我了解您的问题,这应该可行:

      select a.col1 
      from t as a 
      where 
        a.col1 = 56   
        and not exists(select 1 from t as b 
          where b.col1 = a.col1
            and b.col1 = 11
       )
       and exists(select 1 from t as c 
          where c.col1 = a.col1
            and c.col1 = 59
       )
       group by a.col1 -- maybe you need to eliminate duplicates
      

      为了获得更好的答案,您可以提供有关分布的更多详细信息:

      • col1 和 col2 的组合是唯一的。
      • 表中只有这 3 个不同的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-21
        • 2012-09-26
        • 2021-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多