根据特定条件选择将多个记录分组

时间:2018-10-01 06:47:20

标签: mysql sql

我有桌子:

+----+-------+-------------+
| id | code  | value_check | 
| 1  |  p-01 |  OK         |
| 2  |  p-01 |  NOT OK     |
| 3  |  p-01 |  OK         |          
| 4  |  p-02 |  OK         | 
| 5  |  p-02 |  OK         |  
| 6  |  p-02 |  OK         |
+----+-------+-------------+

如何选择按代码记录哪个'OK'分组,但是如果value_check上有一个或多个'NOT OK',则不需要选择

预期结果:

code
p-02

我尝试查询可以得到结果,但是它非常慢 这是我的查询:

SELECT code FROM table
   WHERE code 
NOT IN (SELECT code FROM table 
WHERE value_check = 'NOT OK' GROUP BY code)
GROUP BY code 

还有其他解决方案吗?

3 个答案:

答案 0 :(得分:1)

尝试以下条件聚合

select code from table
group by code
having sum(case when value_check='NOT OK' then 1 else 0 end)=0

您也可以使用相关子查询来尝试:

demo

SELECT distinct code FROM cte1 a
   WHERE NOT exists (SELECT 1 FROM cte1 b where a.code=b.code and val = 'NOT OK')

答案 1 :(得分:1)

使用OK子句检查总数是否等于值为HAVING的行数。

查询

select `code` from `your_table_name`
group by `code`
having count(*) = sum(`value_check` = 'OK');

Find a demo here

答案 2 :(得分:0)

SELECT DISTINCT x.code
  FROM my_table x
  LEFT
  JOIN my_table y
    ON y.code = x.code
   AND y.value_check = 'not ok'
 WHERE x.value_check = 'ok'
   AND y.id IS NULL