根据下面的数据表,您如何显示这些日期范围的分数:3/10至3/12?
得分的公式是今天的得分=(今天的avg5daysprice * 2.15)/昨天的得分。例如,对于3/10得分=(126.11 * 2.15)/10.36
数据存在于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
答案 0 :(得分:1)
在SQL Server 2012中,您可以使用LAG函数访问上一行中的数据。试试这个:
SELECT symbol
,tdate
,price
,avg5daysprice
,COALESCE((avg5daysprice * 2.15) / LAG(score, 1, NULL) OVER (ORDER BY tdate), score) AS score
FROM YourTable
对于跨RDBMS解决方案,我会选择自我加入。
答案 1 :(得分:0)
CTE是Sql Server中的解决方案,位于代码
之下WITH Value_CTE (symbol, tdate,avg5day, scoreAnt) AS (
SELECT symbol, tdate,avg5day, score
FROM ScoreTable
WHERE score IS NOT NULL
YNION ALL
SELECT B.symbol, B.tdate, B.avg5day, cast(((B.avg5day*2.15)/A.scoreAnt) as decimal(8,2)) as score
FROM value_CTE A
INNER JOIN ScoreTable B ON DATEADD(DAY,-1,B.tdate) = A.tdate
)
-- Define the outer query referencing the CTE name.
SELECT symbol, tdate, avg5day, scoreAnt
FROM value_CTE
结果
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