Hope all the SQL GURUS out there are doing great :)
I am trying to simulate LEAD()
and LAG()
functionality in SQL Server 2008.
This is my scenario: I have a temp table which is populated using the base query with the business logic for mileage. I want to calculate accumulated mileage for each user per day.
The temp table is setup using ROW_NUMBER()
, so I have all the data needed in the temp table except the accumulated mileage.
I have tried using a CTE with the base query and self joining with itself and couldn't get it working. I am attaching the screen shot for the same.
Any help/suggestion would be appreciated.
You are on the right track by joining the table to itself. I included 2 methods of doing this below that should work fine here. The first trick is in your
ROW_NUMBER
, be sure to partition by the user id and sort by the date. Then you can use either anINNER JOIN
with aggregation orCROSS APPLY
to build your running totals.Setting up the data with the partitioned
ROW_NUMBER()
:Use
INNER JOIN
with AggregationUse
CROSS APPLY
for the running totalOutput is the same for each method: