SQL: Selecting IDs that don't have any rows with a certain value for a column

后端 未结 3 1985
慢半拍i
慢半拍i 2021-01-12 21:11

I want to select the distinct IDs (which is associated with multiple rows) that DOESN\'T have any rows where VAL = \'current\'.

For example, in a table like this:

相关标签:
3条回答
  • 2021-01-12 21:24

    You can use having

    SELECT
        id,
        count(*) as Total
    FROM table
    WHERE val <> 'current'
    HAVING Total > 0
    

    Output

    | ID | TOTAL |
    |----|-------|
    | 23 |     5 |  
    

    Fiddle

    0 讨论(0)
  • 2021-01-12 21:27
    SELECT DISTINCT id
    FROM table
    WHERE id NOT IN (SELECT id
                     FROM table
                     WHERE val = 'current')
    

    or:

    SELECT a.id
    FROM table a
    LEFT JOIN table b ON a.id = b.id AND b.val = 'current'
    WHERE b.id IS NULL
    
    0 讨论(0)
  • 2021-01-12 21:38

    If you want to use Having Clause then use like this

    SELECT
        id,
        count(*) as Total
    FROM Status S1
    WHERE val <> 'current'
    GROUP BY id
    HAVING count(*) = (SELECT COUNT(*) FROM Status S2 WHERE S2.id = S1.id)
    
    0 讨论(0)
提交回复
热议问题