问题
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.
回答1:
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
- SQLFiddle Demo
回答2:
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
;
回答3:
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
来源:https://stackoverflow.com/questions/20550594/sql-subtract-column-values-based-on-second-column-value-with-group-by-statement