1
TABLE
id   |   result
==================
1    |   SUCCESS
2    |   FAIL
2    |   SUCCESS
3    |   FAIL
3    |   FAIL
3    |   SUCCESS
4    |   FAIL
5    |   FAIL
5    |   FAIL

I want to select those ids that have at least one 'FAIL' and no 'SUCCESS'. In this example, only id = 4 and id = 5 should be selected.

This query doesn't seem to work since HAVING is not aggregating over anything:

SELECT id, result FROM table WHERE result = 'FAIL' GROUP BY id HAVING result != 'SUCCESS'

Does anyone know how this can be done without using IN clauses?

1 Answer 1

3
SELECT 
    id
    , sum(if(result='SUCCESS', 1, 0)) as cnt_succ
    , sum(if(result='FAIL', 1, 0))    as cnt_fail
FROM 
    table 
GROUP BY
    id
HAVING
    cnt_fail>0 and cnt_succ=0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.