Richu
Richu

Reputation: 5

How to find difference between successive rows of same column in sql server using lag function

Been trying with the following query but i'm getting constant difference

with cte as 
(
select businessentityid,nationalidnumber,SickLeaveHours,LAG(sickleavehours) over (order by businessentityid) as PreviousRow
from HumanResources.Employee
)
select *,DIFFERENCE(sickleavehours,cte.previousrow) from cte

enter image description here

Upvotes: 0

Views: 111

Answers (1)

Arion
Arion

Reputation: 31239

Can you just do this?:

with cte as 
(
select businessentityid,nationalidnumber,SickLeaveHours,LAG(sickleavehours) over (order by businessentityid) as PreviousRow
from HumanResources.Employee
)
select *, sickleavehours - cte.previousrow as difference from cte

Upvotes: 1

Related Questions