有条件地在一个select语句中多次对同一列进行求和?

时间:2010-04-28 21:52:33

标签: sql ms-access 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;

请注意,我目前正在构建最终查询,假设某个位置只有临时员工或支持员工,如果他们也有永久员工。因此,我可以使用永久员工结果作为基表创建联接。鉴于我目前拥有的所有数据,这个假设仍然存在,但理想情况下我想摆脱这种假设。

最后,我的问题。有没有办法将其简化为单个查询,或者最好将其分成多个查询 - 如果没有其他原因可读性。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;