gpt4 book ai didi

sql - 在单个选择语句中有条件地对同一列求和多次?

转载 作者:行者123 更新时间:2023-12-04 21:53:28 25 4
gpt4 key购买 nike

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

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;

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

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

最佳答案

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

关于sql - 在单个选择语句中有条件地对同一列求和多次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2733372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com