假设我们有以下架构的下表。
create table result
(
id int,
task_id int,
test_name string,
test_result string
);
填充在该表上的数据集如下所示。
insert into result
values (1, 1, 'test_a', 'pass'),
(2, 1, 'test_b', 'fail'),
(3, 1, 'test_c', 'pass'),
(4, 1, 'test_d', 'pass'),
(5, 2, 'test_a', 'pass'),
(6, 2, 'test_b', 'pass'),
(7, 2, 'test_c', 'pass'),
(8, 2, 'test_d', 'pass');
基本上,单个任务具有多个测试结果条目。我想检索具有test_b失败但所有其他测试通过的task_id。因此在此示例中,它应仅返回task_id:1。
我已经尝试过EXISTS和HAVING,但在这种情况下似乎不起作用。我是SQL的新手。如何实施?
我将只使用带有having
子句的聚合:
select task_id
from result
group by task_id
having sum(case when test_name = 'test_b' and test_result = 'fail' then 1 else 0 end) = 1 and
sum(case when test_result = 'pass' then 1 else 0 end) = count(*) - 1;
第一个条件验证test_b失败。第二个计数通过次数,它应该比任务的行数少一。
如果您的数据库支持except
(或minus
),则可以使用基于集合的操作:
select task_id
from result
where test_name = 'test_b' and test_result = 'fail'
except
select task_id
from result
where test_name <> 'test_b' and test_result = 'fail'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句