Click here to Skip to main content
16,018,818 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Table Name is Employee

EmpNo EmpName Salary
1 A 2000
2 B 1000
3 C 3000
4 D 2000
5 E 5000

I need to get one more column by adding salary of previous and current row as

NewSal
2000
3000
4000
5000
7000

What I have tried:

Select EmpNo,
EmpName, Salary,(SELECT SUM(salary) FROM Employee e1 WHERE
e1.EmpNo <= e2.EmpNo)as T_Sal
FROM Employee e2

I tried this query but this is giving me the addition of all previous rows
Posted
Updated 24-Oct-17 20:12pm

1 solution

Look at the SQL LAG function: LAG (Transact-SQL) | Microsoft Docs[^] - the link includes examples.
 
Share this answer
 
Comments
Member 13483961 25-Oct-17 2:14am    
lag function giving me error as it is not an inbuilt function in sql server.
I tried lag function:
select EmpNo, EmpName,Salary + lag(Salary,1,0) over(ORDER BY EmpNo) FROM Employee
OriginalGriff 25-Oct-17 3:59am    
Which version of SQL Server are you using? LAG was introduced in the 2012 edition - so it's been out there for over 5 years!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900