Conditionally sum the same column several times in the same select statement?

I have one table that shows employee deployments for various deployment types in a specific location for each month:

ID | Location_ID | Date | NumEmployees | DeploymentType_ID

An example is a few entries:

 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 summarize the different types of people by date so 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 have created a separate request for each type of deployment, which looks like this:

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

We will call this request qSumPermDeployments. Then I use a couple of connections 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;

, , , . , , . , , , .

, , . - - .

+3
2
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
+4

:

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;
+1

Source: https://habr.com/ru/post/1743254/


All Articles