在单个select语句中有条件地对同一列进行多次求和? [英] Conditionally Summing the same Column multiple times in a single select statement?

查看:163
本文介绍了在单个select语句中有条件地对同一列进行多次求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只有一张表格,该表格显示每个月在给定位置的各种部署类型的员工部署:

I have a single table that shows employee deployments, for various types of deployment, in a given location for each month:

ID | Location_ID | Date | NumEmployees | DeploymentType_ID

例如,一些记录可能是:

As an example, a few records might be:

 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

我需要做的是按日期对各种类型的人进行求和,以使结果看起来像这样:

What I need to do is sum the various types of people by date, such that the results look something like this:

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

当前,我为每种部署类型创建了一个单独的查询,如下所示:

Currently, I've created a separate query for each deployment type that looks like this:

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

我们将调用该查询qSumPermDeployments.然后,我使用几个联接来组合查询:

We'll call that query qSumPermDeployments. Then, I'm using a couple of joins to combine the queries:

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;

请注意,我目前正在构建最终查询,其前提是该地点只有临时雇员或支持雇员(如果他们也有固定雇员).因此,我可以使用永久雇员结果作为基表来创建联接.鉴于我目前拥有的所有数据,该假设成立了,但理想情况下,我希望脱离该假设.

Note that I'm currently constructing that final query under the assumption that a location will only have temp or support employees if they also have permanent employees. Thus, I can create the joins using the permanent employee results as the base table. Given all of the data I currently have, that assumption holds up, but ideally I'd like to move away from that assumption.

最后,我的问题.有没有一种方法可以简化为单个查询,还是最好将其分为多个查询-如果没有其他原因使可读性如此.

So finally, my question. Is there a way to simplify this down to a single query or is it best to separate it out into multiple queries - if for no other reason that readability.

推荐答案

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

这篇关于在单个select语句中有条件地对同一列进行多次求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆