TABLE id | result ================== 1 | SUCCESS 2 | FAIL 2 | SUCCESS 3 | FAIL 3 | FAIL 3 | SUCCESS 4 | FAIL 5 | FAIL 5 | FAIL
我想选择那些至少有一个'FAIL'而不是'SUCCESS'的ID。在此示例中,只应选择id = 4和id = 5。
此查询似乎不起作用,因为HAVING没有聚合任何内容:
SELECT id,result FROM table WHERE result ='FAIL'GROUP BY id HAVING result!='SUCCESS'
有没有人知道如何在不使用IN子句的情况下完成这项工作?
答案 0 :(得分: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