2017-07-06 104 views
-1

有2個單獨的SQL查詢返回NetPay金額MonthWise。 I 想要合併它們意味着我想要2個月的差異 (第2個月金額 - 第1個月金額)作爲輸出。SQL - 2個月之間的薪酬差異(差異)

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 
+0

Downvoter還提供原因 – Dilip

回答

2

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

+0

你不能修復月ID – Dilip

+0

@Dilip你正在使用哪個版本的SQL服務器? –

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 
+0

工作不正常 – Dilip

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 [email protected] 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 [email protected] GROUP BY EPS.Emp_Id)b 
on a.Emp_Id=b.Emp_Id 

您可以動態提供月份。希望這個作品

+0

給出錯誤: 消息8120,級別16,狀態1,行8 列'Employee_PaySlip.Emp_Id'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 – Dilip

+0

現在檢查..我編輯了代碼。 –