mysql - How to obtain a value from previous day in a query -
given data table below, how can show score these date range: 3/10 3/12?
the formula score today's score=(today's avg5daysprice *2.15)/ yesterday's score. example 3/10 score = (126.11*2.15)/10.36
the data lives in both sql server , mysql.
symbol tdate price avg5daysprice score ----------------------------------------------- aapl 3/9/2015 127.14 126.6, 10.36 aapl 3/10/2015 125.32 126.11 null aapl 3/11/2015 128.15 127.25 null aapl 3/12/2015 124.48 125.66 null
cte solution in sql server, below code
with value_cte (symbol, tdate,avg5day, scoreant) ( select symbol, tdate,avg5day, score scoretable score not null ynion select b.symbol, b.tdate, b.avg5day, cast(((b.avg5day*2.15)/a.scoreant) decimal(8,2)) score value_cte inner join scoretable b on dateadd(day,-1,b.tdate) = a.tdate ) -- define outer query referencing cte name. select symbol, tdate, avg5day, scoreant value_cte
result
symbol tdate avg5day scoreant aapl 2015-03-09 126.60 10.36 aapl 2015-03-10 126.11 26.17 aapl 2015-03-11 127.25 10.45 aapl 2015-03-12 125.66 25.85
Comments
Post a Comment