您可以使用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