【问题标题】:Select all values matching several values in second column选择与第二列中的多个值匹配的所有值
【发布时间】:2019-06-06 19:24:54
【问题描述】:

我有一张这样的桌子:

    ID       VALUE

--------------------
     A   |    abc       <---  
--------------------
     A   |    def       <---
--------------------
     A   |    ghi       <---
--------------------
     B   |    abc       x
--------------------
     C   |    abc       x
--------------------
     C   |    def       x
--------------------
     C   |    xyz       x
--------------------       
     D   |    abc       <---
--------------------
     D   |    def       <---
--------------------
     D   |    ghi       <---

我想选择一个 ID 与所有值匹配的所有 ID (abc, def AND ghi)

结果应该是

A 
D

【问题讨论】:

    标签: sql oracle select


    【解决方案1】:

    您可以使用条件聚合:

    select id
    from t
    where value in ('abc', 'def', 'ghi')
    group by id
    having count(*) = 3;
    

    如果您可以有重复的 id/value 对,请使用 count(distinct id) 而不是 count(*)

    如果表中只有三个值,则可以省略where。或者,如果您想要表中的所有值:

    select id
    from t
    group by id
    having count(*) = (select count(distinct value) from t)
    

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多