SELECTING with multiple WHERE conditions on same column

后端 未结 12 925
南旧
南旧 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:32

    Sometimes you can't see the wood for the trees :)

    Your original SQL ..

    SELECT contactid 
     WHERE flag = 'Volunteer' 
       AND flag = 'Uploaded'...
    

    Should be:

    SELECT contactid 
     WHERE flag = 'Volunteer' 
       OR flag = 'Uploaded'...
    
    0 讨论(0)
  • 2020-11-22 07:33

    your code :

    SELECT contactid 
    WHERE flag = 'Volunteer' AND flag = 'Uploaded' [...]
    

    will not work, for you did not declare the table name. the execution will return an error message.

    and if you want both search query to display, your code should look something like this.

    SELECT * FROM (your_table_name) WHERE flag = 'Volunteer' OR flag = 'Uploaded';
    

    and not like this because it will always return false SELECT * FROM (your_table_name) WHERE flag = 'Volunteer' AND flag = 'Uploaded';

    you can also do this

    SELECT * FROM (your_table_name) 
    WHERE flag = 'Volunteer' OR flag = 'Uploaded' 
    ORDER BY contactid, flag asc; 
    

    (asc for ascending order, you can also change it to desc if you want it to display in descending order)

    0 讨论(0)
  • 2020-11-22 07:36

    Change AND to OR. Simple mistake. Think of it like plain English, I want to select anything with that equals this or that.

    0 讨论(0)
  • 2020-11-22 07:37

    AND will return you an answer only when both volunteer and uploaded are present in your column. Otherwise it will return null value...

    try using OR in your statement ...

    SELECT contactid  WHERE flag = 'Volunteer' OR flag = 'Uploaded'
    
    0 讨论(0)
  • 2020-11-22 07:39
    SELECT contactid, Count(*) 
    FROM <YOUR_TABLE> WHERE flag in ('Volunteer','Uploaded')  
    GROUP BY contactid 
    HAVING count(*)>1;
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题