SQL - 2个月之间的薪水差异(差异)

时间:2017-07-06 11:00:40

标签: sql sql-server

有2个单独的SQL查询返回NetPay金额MonthWise。一世 想要结合它们意味着我想要2个月之间的差异 (第2个金额 - 第1个月金额)作为输出。

Query - 1
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

Query - 2
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6

3 个答案:

答案 0 :(得分:2)

DECLARE @month1 INT
DECLARE @month2 INT

SET @month1= 5
SET @month2= 6

Select (a.month1Amount-b.month2Amount) AS Variance from
(Select ISNULL(Sum(EPS.Amount),0) as month1Amount,EPS.Emp_Id
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id =@month1 GROUP BY EPS.Emp_Id)a
INNER JOIN 
(Select ISNULL(Sum(EPS.Amount),0) as month2Amount, EPS.Emp_Id
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id =@month2  GROUP BY EPS.Emp_Id)b
on a.Emp_Id=b.Emp_Id

您可以动态提供月份。希望这有效

答案 1 :(得分:1)

您可以使用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窗口函数

答案 2 :(得分:0)

如果您不想加入相同的查询以获得更好的可见性,请使用Union all

Select Amount1-Amount As Variance
from 
(
Select ISNULL(Sum(EPS.Amount),0) as Amount, '0.00' Amount1
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

UNION ALL 

Select '0.00' Amount, ISNULL(Sum(EPS.Amount),0) as Amount1
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6

)am