Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created June 1, 2017 23:15
Show Gist options
  • Save MikeMKH/8fd86c28670b09eb959ac8ed1be08cf5 to your computer and use it in GitHub Desktop.
Save MikeMKH/8fd86c28670b09eb959ac8ed1be08cf5 to your computer and use it in GitHub Desktop.
TSQL example of using windowing functions with frames
select
pricingdate
,price
,max(price) over (partition by cusip
order by pricingdate
rows between 30 preceding and current row) as max_price
,min(price) over (partition by cusip
order by pricingdate
rows between 30 preceding and current row) as min_price
,avg(price) over (partition by cusip
order by pricingdate
rows between 30 preceding and current row) as avg_price
,stdev(price) over (partition by cusip
order by pricingdate
rows between 30 preceding and current row) as stdev_price
,var(price) over (partition by cusip
order by pricingdate
rows between 30 preceding and current row) as var_price
,lag(price, 1) over (partition by cusip
order by pricingdate) as lag_price
,lead(price, 1) over (partition by cusip
order by pricingdate) as lead_price
from dbo.security
order by pricingdate
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment