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 に答える