Skip to content

Instantly share code, notes, and snippets.

@royashbrook
Created June 10, 2020 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save royashbrook/ac059ff0359a23bc5c5227bb7881d90b to your computer and use it in GitHub Desktop.
Save royashbrook/ac059ff0359a23bc5c5227bb7881d90b to your computer and use it in GitHub Desktop.
Lag for same day last month with fix for missing end of month days
/* don't lock, be deadlock victim if needed */
set transaction isolation level read uncommitted
set deadlock_priority -10
/* generate sales data */
declare @SalesByDay as table (
[SalesDate] datetime not null primary key
, [TotalSales] decimal(19,2) not null
)
declare @mindate date = '20200101', @maxdate date = '20200630'
;with Dates([Date]) as (
select @mindate
union all
select dateadd(day, 1, [Date])
from Dates
where [Date] < @maxdate
)
, SalesByDay([Date],[Sales]) as (
select *, CAST(RAND(CHECKSUM(NEWID()))*100000 as decimal(19,2))
from Dates
)
insert into @SalesByDay
select * from SalesByDay
option (maxrecursion 0)
/* show our example and fix */
select
[SalesDate] = cast(format([SalesDAte],'yyyy-MM-dd') as varchar(10))
, [TotalSales]
, [SalesPrev] =
lag([TotalSales]) over (partition by day([SalesDate]) order by [SalesDate])
, [Fixed] =
case
when day([SalesDate]) <= day(eomonth(dateadd(month,-1,[SalesDate])))
then lag([TotalSales]) over (partition by day([SalesDate]) order by [SalesDate])
end
from
@SalesByDay
where
day([SalesDate]) in (29,30,31)
order by
SalesDate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment