根据现有结果获取派生状态列的最佳方法是什么

What is the best way to get a derived status column based on existing result

我有一个 table :

------------------------
testId |    runId   |result 
------------------------
**1    | 11         |0**
**1    | 12         |1**
**1    | 13         |1**
**1    | 14         |1**
**2    | 21         |0**
**3    | 31         |1**
**4    | 41         |1**
**4    | 42         |1**
**4    | 43         |1**
**5    | 51         |0**
**5    | 52         |0**
**5    | 53         |0**
**6    | 61         |1**
**6    | 62         |0**
**6    | 63         |1**

一个测试可以有多个run/execution。每个 运行 都有一个结果。这里对于结果列,0 是失败,1 是通过。 我要查询 --如果测试全部运行 PASS,则OverallStatus为PASS --如果一个测试全部运行失败,则OverallStatus为FAIL --如果其中一些通过,而另一些失败,则 OverallStaus 为 DEFECT

我想从上面table得到一个输出,比如

testId |numOfRun |OverallStatus

1 | 4 |缺陷

2 | 1 |失败

3 | 1 |通过

4 | 3 |通过

5 | 3 |失败

6 | 3 |缺陷



您可以使用条件聚合

select testId,
       numOfRun,
case when numOfRun = pass then 'pass'
    when numOfRun = fail then 'fail'
    else 'defect'
    end as OverallStatus 
from (
    select testId,
    count(*) numOfRun,
    sum(case when result = 0 then 1 else 0 end) as fail,
    sum(case when result = 1 then 1 else 0 end) as pass
    from table
    group by testId 
) t

我建议一步完成:

select testid,
       (case when min(result) = 1 then 'Pass'
             when max(result) = 0 then 'Fail'
             else 'Defect'
        end) as overall_status
from t
group by testid;

编辑:

根据您的评论:

select testid,
       (case when min(result) = N'TestSuccess' then 'Pass'
             when max(result) = N'TestFailure' then 'Fail'
             else 'Defect'
        end) as overall_status
from t
group by testid;