2010-04-28 47 views
3

我有一個表,顯示員工的部署,爲不同類型的部署,在每月指定位置:有條件地在單個select語句中多次合計相同的列?

ID | Location_ID | Date | NumEmployees | DeploymentType_ID 

舉個例子,一些記錄可能是:

1 | L1 | 12/2010 | 7 | 1 (=Permanent) 
2 | L1 | 12/2010 | 2 | 2 (=Temp) 
3 | L1 | 12/2010 | 1 | 3 (=Support) 
4 | L1 | 01/2011 | 4 | 1 
5 | L1 | 01/2011 | 2 | 2 
6 | L1 | 01/2011 | 1 | 3 
7 | L2 | 12/2010 | 6 | 1 
8 | L2 | 01/2011 | 6 | 1 
9 | L2 | 12/2010 | 3 | 2 

我需要做的是按日期總結不同類型的人,這樣的結果是這個樣子:

Date | Total Perm | Total Temp | Total Supp 
12/2010 |  13  |  5  |  1 
01/2011 |  10  |  2  |  1 

目前,我已經創建對於像這樣每個部署類型都有一個單獨的查詢:

SELECT Date, SUM(NumEmployees) AS "Total Permanent" 
FROM tblDeployment 
WHERE DeploymentType_ID=1 
GROUP BY Date; 

我們會打電話給該查詢qSumPermDeployments。然後,我用一對夫婦的聯接到查詢組合:

SELECT qSumPermDeployments.Date, qSumPermDeployments.["Total Permanent"] AS "Permanent" 
    qSumTempDeployments.["Total Temp"] AS "Temp" 
    qSumSupportDeployments.["Total Support"] AS Support 
FROM (qSumPermDeployments LEFT JOIN qSumTempDeployments 
    ON qSumPermDeployments.Date = qSumTempDeployments.Date) 
LEFT JOIN qSumSupportDeployments 
    ON qSumPermDeployments.Date = qSumSupportDeployments.Date; 

請注意,我目前正在建設的假設下最終查詢的地點將只具有臨時或支持的員工,如果他們也有永久僱員。因此,我可以使用永久員工結果作爲基本表創建連接。考慮到我目前掌握的所有數據,這個假設依然存在,但理想情況下,我想擺脫這種假設。

最後,我的問題。有沒有一種方法可以簡化爲單個查詢,還是最好將其分解爲多個查詢 - 如果沒有其他原因可讀性。

回答

4
SELECT Date, 
    SUM(case when DeploymentType_ID = 1 then NumEmployees else null end) AS "Total Permanent", 
    SUM(case when DeploymentType_ID = 2 then NumEmployees else null end) AS "Total Temp", 
    SUM(case when DeploymentType_ID = 3 then NumEmployees else null end) AS "Total Supp" 
FROM tblDeployment 
GROUP BY Date 
+0

+1:11只在你身後秒這段時間...我越來越近。 :) – 2010-04-28 21:57:06

+0

@Mark:大聲笑,upvote那 – RedFilter 2010-04-28 22:23:10

+0

哇!我真的走了很長的路。謝謝你的幫助。 – wtollett 2010-04-28 22:25:29

1

試試這個:

SELECT 
    Date, 
    SUM(CASE WHEN DeploymentType_ID=1 THEN NumEmployees ELSE 0 END) AS "Total Permanent", 
    SUM(CASE WHEN DeploymentType_ID=2 THEN NumEmployees ELSE 0 END) AS "Total Temporary", 
    SUM(CASE WHEN DeploymentType_ID=3 THEN NumEmployees ELSE 0 END) AS "Total Support" 
FROM tblDeployment 
GROUP BY Date; 
相關問題