查询多行到摘要结果

时间:2014-10-24 15:26:56

标签: sql

我尝试查询每个ID的失败结果的传递,该表如下所示,每个部分有0到3个通道并且有结果。如果所有通道都通过,我需要检查每个ID对于该ID,结果将被传递,否则,它将失败

ID   result     Channel
ID1  FAIL        2
ID1  PASS        1
ID1  FAIL        0
ID2  PASS        1
ID2  PASS        3
ID2  PASS        2
ID2  PASS        0
ID3  FAIL        0
ID3  PASS        1
ID3  PASS        2
ID3  FAIL        3
ID4  FAIL        1
ID4  PASS        0
ID4  PASS        3
ID4  FAIL        2

3 个答案:

答案 0 :(得分:1)

select ID, result, count(Channel)
from t
group by ID, result
having result = 'PASS' and count(Channel) = 3
union all
select ID, result, count(Channel) 
from t
group by ID, result
having result = 'FAIL';

如果不是每个ID都有3个频道,那么

select ID, result, count(Channel)
from t t1 where not exists (select 1 from t t2 where t1.id = t2.id and t2.result = 'FAIL')
group by ID, result
union all
select ID, result, count(Channel) 
from t
group by ID, result
having result = 'FAIL';

对于性能竞争(如果在您的数据库中失败''通过'如果不是,请使用最大):

select ID, min(result) n
from t
group by ID;

答案 1 :(得分:0)

因为'失败'低于' PASS'

SELECT ID,MIN(result) AS result from yourtable group by id

如果不是每个ID都有3个频道,那么

SELECT ID,case when count(id)=4 then MIN(result) else 'FAIL' end AS result  from yourtable group by id

答案 2 :(得分:0)

这应该这样做,并且感谢common table expressions,它也很可读:

WITH bar AS (
    SELECT
        ID
        , channel
        , COUNT(result) AS result_count
        , SUM(CASE WHEN result = 'PASS' THEN 1 ELSE 0 END) AS pass_count
    FROM foo
    GROUP BY ID, channel
)

SELECT
    ID
    , channel
    , CASE WHEN result_count = pass_count THEN 'PASS' ELSE 'FAIL' END AS overall_result
FROM bar;

SQLFiddle