简体   繁体   中英

SQL Subtract Column Values Based on Second Column Value with Group By Statement

I have an SQL statement that looks so:

select FY_CD, PD_NO, INPUT, SUM(HOURS) 
from LABOR_TABLE
group by PD_NO, INPUT;

Returning this:

FY_CD|PD_NO| INPUT |    HOURS

2008    1   Actuals     61000
2008    1   Baseline    59000
2008    2   Actuals     54000
2008    2   Baseline    59000
2008    3   Actuals     60000
2008    3   Baseline    70000

I'm trying to figure out how to subtract the Actual values from the Baseline values for each period, returning the following:

FY_CD|PD_NO| INPUT |    HOURS

2008    1   Variance    2000
2008    2   Variance    -5000
2008    3   Variance    -10000

Any help is appreciated.

You can actually calculate it directly by using CASE to check the value of Input ,

SELECT  FY_CD, 
        PD_NO, 
        'Variance' INPUT, 
        SUM(CASE WHEN Input = 'Actuals' THEN HOURS ELSE -1 * HOURS END) HOURS
FROM    LABOR_TABLE
GROUP   BY PD_NO

You can use subqueries to divide the table into two parts and then join the parts so that the Actuals and Baselines are on the same row (by PD_NO). Then it's just simple subtraction.

SELECT      Baseline.FY_CD
        ,   Baseline.PD_NO
        ,   SUM(Baseline.HOURS - Actuals.Hours)
FROM        ( SELECT * FROM LABOR_TABLE WHERE INPUT = 'Baseline' ) AS Baseline
JOIN        ( SELECT * FROM LABOR_TABLE WHERE INPUT = 'Actuals' ) AS Actuals
        ON  Actuals.PD_NO = Baseline.PD_NO
GROUP BY    Baseline.PD_NO
;

I believe this would work. Basically I'm trying to subquery your Baseline and Actuals values so I can group them into the same row to subtract one from the other.

SELECT FY_CD, PD_NO, 'Variance' As Input, tmp.Actuals - Baseline As Hours FROM (
 select FY_CD, PD_NO,
 (SELECT SUM(HOURS) from LABOR_TABLE WHERE Input = 'Actuals' group by PD_NO, INPUT) As Actuals,
 (SELECT SUM(HOURS) from LABOR_TABLE WHERE Input = 'Baseline' group by PD_NO, INPUT) As Baseline,
 group by PD_NO, INPUT
) as tmp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM