如何改进此SQL查询?

时间:2013-01-09 06:38:35

标签: sql

我是新手,我有一张表来存储一些测试结果。

列可以简化为2列:

EXECUTION_ID int(6) CASE_ID int(11)
RESULT varchar(10).

“RESULT”列实际上是一个枚举,将值保存在'PASS',* 'FAIL''NORESULT' *

现在我想使用一个sql查询来获取所有执行的统计信息。

结果集格式如:

EXECUTION_ID | PASS_CNT FAIL_CNT  |  NORESULT_CNT

我只能找到一种方法来实现它:

select A.execId,A.a,B.a,C.a from
    (select execId,result,count(result) a from STAT_RESULTS group by execId,result having result='PASS') A left join
    (select execId,result,count(result) a from STAT_RESULTS group by execId,result having result='FAIL') B on A.execId=B.execId left join
    (select execId,result,count(result) a from STAT_RESULTS group by execId,result having result='NORESULT') C on A.execId=C.execId;

结果列表如下:

execId  pass    fail    noresult
55      169     77      null
56      46      9       1
57      120     13      3
58      91      45      null
59      95      44      null
60      179     9       5

有没有更好的方法来做同样的事情?

谢谢!

1 个答案:

答案 0 :(得分:1)

怎么样?

select 
s.execid EXECUTION_ID
,sum(case when s.result='PASS' then 1 else 0 end) PASS_CNT 
,sum(case when s.result='FAIL' then 1 else 0 end) FAIL_CNT
,sum(case when s.result='NORESULT' then 1 else 0 end) NORESULT_CNT
from STAT_RESULTS s
group by s.execid