2017-05-06 137 views
0

我有一個場景,在基於狀態和ID的SQL Server數據庫中,我必須對行進行分組並顯示計數。我想,但我得到單獨分開行的值類似下面SQL Server:將多行值分成單行

select 
    req_id as bid, status, 
    (case when status = 1 then 1 else 0 end) as accept, 
    count(case when status = 2 then 1 else 0 end) as rejected, 
    (case when status = 3 then 1 else 0 end) as noResp 
from 
    temp_allo 
group by 
    req_id, status 

結果是

bid status accept rejected noResp 
-------------------------------------- 
1  1  1  1  0 
2  1  1  1  0 
3  1  1  1  0 
2  2  0  2  0 
3  2  0  1  0 

(狀態僅供參考)

但我需要得到這樣的:

bid  accept rejected noResp 
----------------------------------- 
1  1   0   0 
2  1   2   0 
3  1   1   0 

我從stackoverflow得到很多樣本我試過MAX(),SUM(),CASE但我無法讓它工作。

請建議..

+0

如何拒絕= 0爲bid = 1,是不是有一些邏輯問題? – igr

+0

這是一個基於狀態的計數有多少人拒絕從數據庫條目中提取 – Malar

回答

3

因爲你是在旋轉的狀態,因此,我建議,它不應該出現在名單GROUP BY。相反,請彙總req_id,然後使用MAX()和當前的CASE表達式。

select 
    req_id as bid, 
    max(case when status = 1 then 1 else 0 end) as accept, 
    max(case when status = 2 then 1 else 0 end) as rejected, 
    max(case when status = 3 then 1 else 0 end) as noResp 
from temp_allo 
group by req_id 
+0

其工作謝謝! – Malar