Created
June 10, 2020 16:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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