DECLARE @Employee table (Employee_ID int, Name varchar(100), JoiningSalary int, JoiningDate date)
insert @Employee
SELECT 1, 'a', 1800, '2008-06-30' union all
SELECT 2, 'b', 2000, '2007-07-01'
DECLARE @SalaryHike table (ID int, Employee_ID int, SalaryHikePercentage int, HikeDate date, Comments varchar(100))
INSERT @SalaryHike
SELECT 1, 1, 10, '2009-04-01', 'Hike' union all
SELECT 2, 2, 5, '2008-04-01', 'Hike' union all
SELECT 3, 1, 5, '2009-10-30', 'Bonus' union all
SELECT 4, 1, 10, '2010-04-30', 'Hike' union all
SELECT 5, 2, 15, '2010-04-30', 'Hike' union all
SELECT 6, 1, 10, '2011-04-30', 'Hike'
--Declaration of required variables
DECLARE @EmpID int = 1 -- enter the employee ID
,@SAL DEC(18,2)
,@DOJ date
,@Inc dec(18,2)
,@TotSal dec(18,2)=0
--fetch joining date and salary of an employee
SELECT @SAL = JoiningSalary , @DOJ = JoiningDate
FROM @Employee
WHERE Employee_ID = @EmpID
--query to sum up the salary paid to an employee
;With CteEMpHike As
(
SELECT @EmpID as Employee_ID, 0 as SalaryHikePercentage, @DOJ as HikeDate, '' as Comments
UNION ALL
SELECT Employee_ID, SalaryHikePercentage, HikeDate, Comments
FROM @SalaryHike WHERE Employee_ID=@EmpID
)
SELECT @Inc = ISNULL(@Inc,@SAL) + ((ISNULL(@Inc, @SAL)*SalaryHikePercentage)/100.0)
,@TotSal = ISNULL(@TotSal,@Inc) + @Inc*(DATEDIFF(DD, HikeDate,ISNULL(LEAD(HikeDate) OVER(ORDER BY HikeDate), GETDATE() ))/30) --summed up the salary of an employee from last hikedate to till date also
from CteEMpHike
WHERE Employee_ID = @EmpID
SELECT @TotSal TotalPaidSalaryForEmp, @EmpID as EmpID
Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif
Sriharim, if this helps please login to Mark As Answer. | Alert Moderator