我有这样的表格,我希望如下所述实现
EffectiveStartDate PayElementCode ElementAmount
04/01/2013 Basic 14534
04/01/2013 HRA 5814
04/01/2013 Education Allowance 200
04/01/2013 Special Allowance 2075
04/01/2013 Transportation Allowance 800
04/01/2013 Helper Allowance 3500
04/01/2013 Uniform Allowance 750
04/01/2013 LTA / LTC 2083
04/01/2013 Medical Exp. 1250
04/01/2014 Helper Allowance 3500
04/01/2014 Medical Exp. 1250
04/01/2014 Tel & Mobile Exp. 600
04/01/2014 Petrol Running & Repairs 2500
04/01/2014 Attire Purchase 1667
04/01/2014 LTA / LTC 2083
如何实现以下输出写入查询。
EffectiveStartDate Amount DiffAmount
2013-04-01 36335.00 0
2014-04-01 44085.00 7750
答案 0 :(得分:0)
我实现了
;WITH CTE AS (
SELECT
rownum = ROW_NUMBER() OVER (ORDER BY p.EffectiveStartDate),MONTH(p.EffectiveStartDate) as MM,YEAR(p.EffectiveStartDate) as YY, SUM(p.ElementAmount) as Salary,p.EffectiveStartDate as EffectiveDate,p.EmployeeID as EmployeeId
FROM tbl_EmployeePayElement p where EmployeeID=@EmployeeId and ISSalary=1 Group By EffectiveStartDate,EmployeeID
)
SELECT
CTE.EmployeeId, CTE.EffectiveDate, CTE.MM,CTE.YY,
CTE.Salary,ISNULL(CTE.Salary-prev.Salary,0) as Diff
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1