2013-04-10 78 views
0

這是我的腳本這個select語句的正確sql腳本是什麼?

SELECT iBranch_num, 
    CASE WHEN iPatient_typ=1 THEN COUNT(iPatient_num) ELSE 0 END AS [New Patient], 
    CASE WHEN iPatient_typ=2 THEN COUNT(iPatient_num) ELSE 0 END AS [Buying Patient],     
    CASE WHEN iPatient_typ=3 THEN COUNT(iPatient_num) ELSE 0 END AS [Active Patient], 
    CASE WHEN iPatient_typ=4 THEN COUNT(iPatient_num) ELSE 0 END AS [Inactive Patient] 
FROM tblsotransaction 
WHERE iStatus_typ=1 
    AND iApply_dt BETWEEN 20130401 AND 20130408 
    AND iBranch_num=14 
GROUP BY iBranch_num, iPatient_typ 

當前結果:

14, 25, 0, 0, 0 
14, 0, 8, 0, 0 
14, 0, 0, 97, 0 
14, 0, 0, 0, 2 

我想要的結果是這樣

14, 25, 8, 9, 2 
+0

什麼RDBMS使用的是?它是SQL服務器嗎? – 2013-04-10 00:27:20

+0

SQL SERVER 2000 – 2013-04-10 00:32:42

回答

2

裹聚合函數COUNT裏面全CASE表達,從GROUP BY子句刪除iPatient_typ

SELECT 
    iBranch_num, 
    COUNT(CASE WHEN iPatient_typ=1 THEN iPatient_num ELSE 0 END) AS [New Patient], 
    COUNT(CASE WHEN iPatient_typ=2 THEN iPatient_num ELSE 0 END) AS [Buying Patient],     
    COUNT(CASE WHEN iPatient_typ=3 THEN iPatient_num ELSE 0 END) AS [Active Patient], 
    COUNT(CASE WHEN iPatient_typ=4 THEN iPatient_num ELSE 0 END) AS [Inactive Patient] 
FROM tblsotransaction 
WHERE iStatus_typ = 1 
    AND iApply_dt BETWEEN 20130401 AND 20130408 
    AND iBranch_num = 14 
GROUP BY iBranch_num; 

或者:SUM

SELECT 
    iBranch_num, 
    SUM(CASE WHEN iPatient_typ = 1 THEN 1 ELSE 0 END) AS [New Patient], 
    SUM(CASE WHEN iPatient_typ = 2 THEN 1 ELSE 0 END) AS [Buying Patient], 
    SUM(CASE WHEN iPatient_typ = 3 THEN 1 ELSE 0 END) AS [Active Patient], 
    SUM(CASE WHEN iPatient_typ = 4 THEN 1 ELSE 0 END) AS [Inactive Patient] 
FROM tblsotransaction 
WHERE iStatus_typ = 1 
    AND iApply_dt BETWEEN 20130401 AND 20130408 
    AND iBranch_num = 14 
GROUP BY iBranch_num; 
+0

我得到了與這個acript相同的結果 – 2013-04-10 00:35:48

+0

@odlanyer - 對不起,從'GROUP BY'子句中刪除'iPatient_typ',我更新了我的答案。 – 2013-04-10 00:37:22

+0

在你的第一個答案我qot一個錯誤! – 2013-04-10 00:40:27

相關問題