Three day average for each row:
with top3Values as
(
select t.ticker, t.dt_date, top3.volume
from yourtable t
outer apply
(
select top 3 top3.volume
from yourtable top3
where t.ticker = top3.ticker
and t.dt_date >= top3.dt_date
order by top3.dt_date desc
) top3
)
select ticker, dt_date, ThreeDayVolume = avg(volume)
from top3Values
group by ticker, dt_date
order by ticker, dt_date
Latest value:
with tickers as
(
select distinct ticker from yourtable
), top3Values as
(
select t.ticker, top3.volume
from tickers t
outer apply
(
select top 3 top3.volume
from yourtable top3
where t.ticker = top3.ticker
order by dt_date desc
) top3
)
select ticker, ThreeDayVolume = avg(volume)
from top3Values
group by ticker
order by ticker
Realistically you wouldn't need to create the tickers CTE for the second query, as you'd be basing this on a [ticker]
table, and you'd probably have some sort of date
parameter in the query, but hopefully this will get you on the right track.