SELECTING with multiple WHERE conditions on same column

后端 未结 12 931
南旧
南旧 2020-11-22 07:00

Ok, I think I might be overlooking something obvious/simple here... but I need to write a query that returns only records that match multiple criteria on the same column...<

12条回答
  •  既然无缘
    2020-11-22 07:41

    Use:

      SELECT t.contactid
        FROM YOUR_TABLE t
       WHERE flag IN ('Volunteer', 'Uploaded')
    GROUP BY t.contactid
      HAVING COUNT(DISTINCT t.flag) = 2
    

    The key thing is that the counting of t.flag needs to equal the number of arguments in the IN clause.

    The use of COUNT(DISTINCT t.flag) is in case there isn't a unique constraint on the combination of contactid and flag -- if there's no chance of duplicates you can omit the DISTINCT from the query:

      SELECT t.contactid
        FROM YOUR_TABLE t
       WHERE flag IN ('Volunteer', 'Uploaded')
    GROUP BY t.contactid
      HAVING COUNT(t.flag) = 2
    

提交回复
热议问题