Search code examples
mysqlcountcriteriadistinct

Return only the values that match a certain criteria


I have

ID   Rank

11   1  
11   2  
22   1  
22   2  
22   3  
33   1  
33   3  
44   1  
55   1  
55   2  

I Want

11  
44  
55  

That is, I want to return only the IDs that have never been in a rank of '3'.

UPDATE - I figured another way, rather simpler, to do this in addition to the answer below.

SELECT ID FROM
(  
  SELECT ID, SUM(CASE WHEN Rank = 3 THEN 1 ELSE 0 END) flag FROM 
  (  
    SELECT ID, Rank FROM T1
  ) a  
  GROUP BY ID    
) b  
WHERE flag = 0;  

Solution

  • Using NOT EXISTS:

    SELECT DISTINCT
        yt1.ID
    FROM
        yourTable yt1
    WHERE
        NOT EXISTS (
            SELECT *
            FROM yourTable yt2
            WHERE 
                yt1.ID = yt2.ID 
                AND yt2.Rank = 3
        )
    

    Or, using LEFT JOIN:

    SELECT DISTINCT
        yt1.ID
    FROM
        yourTable yt1
        LEFT JOIN yourTable yt2 ON yt1.ID = yt2.ID AND yt2.Rank = 3
    WHERE
        yt2.ID IS NULL