2013-03-18 65 views
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
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 
+0

THANKS可以喲幫助我如何caluclate安全 – Ram 2013-03-18 15:09:54

+0

(安全)的%/安全+不安全* 100 – Ram 2013-03-18 15:10:38

+0

這必須是在我的答案中包含一個外部查詢(或者來自@AlexanderFedornko的答案,這也將起作用)。您只能計算總計的百分比,而不是單個行。另外,由於'na'狀態,你必須防止零分。就像'SELECT safe /(safe + unsafe)FROM()WHERE safe + unsafe <> 0'。或者,您可以跳過'WHERE safe + unsafe <> 0'檢查是否通過將where子句更改爲WHERE TRAINING_RESULT_ID IN(1,2)'來省略內部查詢中的'na'狀態。 – 2013-03-18 15:23:51

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 
相關問題