Back to Blog

SQL INTO

Prior Day Profit using the Lag Function with Windowing in SQL Server

Compare values across rows with LAG function. Learn window functions for time-series analysis and day-over-day calculations in SQL Server.

1 min read

Last updated on

You can get a prior day value using the Lag Function in SQL Server.

In this video I show you how to create a prior day squeeze of profit using the Windowing Lag function in TSQL.

This video builds on the prior day’s video, Moving Average with Windowing.

I use the Wide World Importers and the following scripts:

select

[Invoice Date Key],

Profit,

Lag(Profit,1) OVER (ORDER BY [Invoice Date Key]) as PriorDayProfit,

Profit - isnull(Lag(Profit,1) OVER (ORDER BY [Invoice Date Key]),0) as DailySqueeze

from dbo.ProfitByDate

order by 1

Link to the Microsoft SQL Server Over Clause.

See the original SQL Prior Day Profit - Lag Windowing Function video.

About Joey Blue

Joey Blue teaches practical data skills that companies actually use. With 25+ years of experience solving real data problems for Fortune 500 companies, he's helped 152,000+ students learn SQL, Power BI, reporting, and modern analytics—cutting straight to what works.