您可以使用Conditional Aggregation
到这两个查询
Select Sum(case EPS.Month_Id when 6 then EPS.Amount else -EPS.Amount end) as Variance
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id in (6,5)
或
Select Sum(case EPS.Month_Id when 6 then EPS.Amount else 0 end) -
Sum(case EPS.Month_Id when 5 then EPS.Amount else 0 end)
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id in (6,5)
结合可以在where
条款和Case
声明更换个月,如果它是不固定的。
使用几个月动态
SELECT Isnull(A.Amount, 0) - Isnull(B.amount, 0)
FROM (SELECT months,
Amount = Sum(Amount)
FROM #payslips
GROUP BY months) a
INNER JOIN (SELECT months,
Amount = Sum(Amount)
FROM #payslips
GROUP BY months) b
ON a.months = b.months + 1
WHERE a.months = 6
AND b.months = 5
的另一种方法对于较新的版本中,我们可以使用LAG
窗函数
Downvoter还提供原因 – Dilip