选择按特定条件分组多条记录

9q78igpj  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(294)

我有一张table:

+----+-------+-------------+
| 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' 按代码分组,但如果有一个或多个 '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

还有别的解决办法吗?

ldxq2e6h

ldxq2e6h1#

使用条件聚合尝试以下操作

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

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

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

n53p2ov02#

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
ddrv8njm

ddrv8njm3#

检查总计数是否等于值为的行数 OK 使用 HAVING 条款。
查询

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

在此处查找演示

相关问题