SQL根据值

时间:2017-12-15 14:26:08

标签: sql h2

我现在有点挑战。我有下表:

 | ID | STATUS   | 
   12   COMPLETE 
   12   FAIL  
   11   COMPLETE

我需要选择的是状态完成的不同ID。如果状态为“失败”,我不希望看到该ID返回给我。

我试过这个:

 select distinct id where status = 'COMPLETE'

然而,这返回给我,因为id 12的状态在一行上完成所有行。我希望它不返回该行,因为12也有一个失败(我只想返回给定ID的所有状态为“COMPLETE”的行。)

有人对此有任何指示吗?非常感谢任何帮助!

祝你好运, 瑞典王子

3 个答案:

答案 0 :(得分:1)

只需添加验证即可确保所有行都具有状态"COMPLETE"

 SELECT id 
 FROM status      
 GROUP BY id
 HAVING count(id) = count( CASE WHEN status = 'COMPLETE' THEN 1 END )

答案 1 :(得分:0)

我会尝试:

SELECT id 
FROM status 
WHERE status = 'COMPLETE' 
GROUP BY id

答案 2 :(得分:0)

这样可行。我们的想法是选择status = complete的行作为第一阶段。然后第二阶段是验证表中是否存在相同ID的另一状态,其中<>比完成。 这意味着它只返回只有一个完成状态的迭代。

declare @table table (id integer, status varchar(max))
insert into @table select 12,'complete'
insert into @table select 12,'fail'
insert into @table select 11,'complete'

select ID, status
from @table t1
where not exists (select 1 from @table t2 where t2.id =t1.id and t1.status <> t2.status)
and t1.status = 'complete'