0

这个查询:

select audit_id, Count(TRAINING_RESULT_ID ) safe
from TBL_T_AUDIT_DETAILS
where TRAINING_RESULT_ID =1 
group by audit_id
order by audit_id

给了我这些结果:

audit_id  safe
117       5
118       3
123       5
130       7
131       39
136       38

这个查询:

select audit_id, Count(TRAINING_RESULT_ID ) unsafe
from TBL_T_AUDIT_DETAILS
where TRAINING_RESULT_ID =2
group by audit_id
order by audit_id

给了我这些结果:

audit_id    unsafe
117           2
118           3
123           2
131           2
136           3
141           3
148           3
151           4
157           4

最后,这个查询:

select audit_id, Count(TRAINING_RESULT_ID ) na
from TBL_T_AUDIT_DETAILS
where TRAINING_RESULT_ID =3
group by audit_id 
order by audit_id

给了我这些结果:

audit_id  na
118      1
147      124
148      8
157      116
218      79
226      47

我怎样才能得到以下结果?

audit_id  na  unsafe  safe
117       0    0       2
118       1    3       3
147       124  0       0
148       8    0       0 
157       116  0       0
218       79   0       0
226       47   0       0
141       0    3       0
148       0    3       0
123       0    0       2
131       0    0       2
136       0    0       3
4

2 回答 2

4
select audit_id, 
 sum(case when TRAINING_RESULT_ID = 1 then 1 else 0 end) safe
 sum(case when TRAINING_RESULT_ID = 2 then 1 else 0 end) unsafe
 sum(case when TRAINING_RESULT_ID = 3 then 1 else 0 end) na
from TBL_T_AUDIT_DETAILS
where TRAINING_RESULT_ID in (1, 2, 3)
group by audit_id
order by audit_id
于 2013-03-18T14:33:21.627 回答
1

也是带有 COUNT() 函数的选项

SELECT audit_id, 
       COUNT(case when TRAINING_RESULT_ID = 1 then TRAINING_RESULT_ID end) safe
       COUNT(case when TRAINING_RESULT_ID = 2 then TRAINING_RESULT_ID end) unsafe
       COUNT(case when TRAINING_RESULT_ID = 3 then TRAINING_RESULT_ID end) na
FROM TBL_T_AUDIT_DETAILS
WHERE TRAINING_RESULT_ID IN (1, 2, 3)
GROUP BY audit_id
ORDER BY audit_id
于 2013-03-18T14:47:28.610 回答