Hi people, i'm using SQL Server 2019 and i've tried for the last month and couldn't get a good answer. I have a table with two columns: date and price, which have a price for each working day for the last 20 years, for about 200 stocks, aproximately 250 * 200 * 20 = 1000000 rows. I just want to transform this two columns table into a new three columns table with a third column standing for the median of the price of the last 90 days. I dont care about the first <90 days of median of the stocks.
I made this query
select * from (
select Date, Product_Id, Price
from Data as d) a
cross apply (
select top 1 PERCENTILE_CONT(0.5) within group (order by Price) over () as PriceMedian
from (
select Price
from Data as d
where d.Product_Id = a.Product_Id
and d.ValDate <= a.ValDate
order by ValDate desc
offset 0 rows fetch next 90 rows only) q) q
It does solves the problem but performs poorly. For the indexes I just made a primary key with Date and Product_id columns which generated the clustered unique index but thats all.
I can't even run the query completely, only select just some few days.
Can anyone help me?