簡體   English   中英

SQL - 在列中查找具有特定值組合的行

[英]SQL - Finding rows with specific combination of values in a column

不確定如何准確表達這個問題,最好通過一個例子來理解。 我試過環顧四周,但無法完全找到我要找的東西。 如果它存在,我很抱歉,如果存在,我很樂意關閉它。

使用 SQL 數據庫,我的數據如下所示:

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

我想找到 col1 的值,在 col2 中,值是 56 和 59 但不是 11。因此上面示例表上的查詢將只返回“C”。

我已經嘗試過窗口和子查詢,如果感覺應該不會太難,但還不夠。 任何提示表示贊賞,謝謝!

我喜歡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' ,這與描述一致。

在執行GROUP BY時,使用WHERE子句僅包含這 3 個值。 使用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

據我了解您的問題,這應該有效:

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 個不同的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM