簡體   English   中英

計算累積產品價值

[英]Calculate cumulative product value

我有以下數據庫表:

Date        Return  Index
01-01-2020  0.1     Null 
01-02-2020  0.2     Null
01-03-2020  0.3     Null

我想使用以下公式更新索引值:

Index = (Previous_Month_Index * Return) + Previous_Month_Index (Use 100 for Previous_Month_Index for the first month)

預期結果:(按日期升序計算的索引)

Date        Return  Index
01-01-2020  0.1     110  -- (100 + 10)
01-02-2020  0.2     132  -- (110 + (110 * 0.20)) = 110 + 22 = 132
01-03-2020  0.3     171.6  -- (132 + (132 * 0.30)) = 132 + 39.6 = 171.6

如何使用 SQL 做到這一點? 我嘗試了以下查詢,但出現錯誤:

窗口函數不能在另一個窗口 function 或聚合的上下文中使用。

--first, load the sample data to a temp table
select *
into #t
from 
(
  values
  ('2020-01-01', 0.10),
  ('2020-02-01', 0.20),
  ('2020-03-01', 0.30)
) d ([Date], [Return]);

--next, calculate cumulative product
select *, CumFactor = cast(exp(sum(log(case when ROW_NUMBER() OVER(order by [Date] ASC)  = 1 then 100 * [Return] else [Return] end)) over (order by [Date])) as float) from #t;

drop table #t

從數學上思考,你想要的結果相當於這個產品:

100 * (1 + a1) * (1 + a2) * (1 + a3) * ....

其中 a1, a2, a3 是[Return]列的值。

該產品可以通過以下方式獲得:

100 * EXP(SUM(LOG(1 + [Return])))

您可以在 sql 中執行此操作,如下所示:

SELECT *, 
       100 * EXP(SUM(LOG(1 + [Return])) OVER (ORDER BY [Date])) [Index]
FROM #t

請參閱演示

遞歸 CTE 可能是最簡單的方法:

with tt as (
      select row_number() over (order by date) as seqnum, date, ret
      from t
     ),
     cte as (
      select seqnum, date, ret, convert(float, (1 + ret) * 100) as runningTotal
      from tt
      where seqnum = 1
      union all
      select tt.seqnum, tt.date, tt.ret, convert(float, (1 + tt.ret) * cte.runningTotal)
      from cte join
           tt
           on tt.seqnum = cte.seqnum + 1
     )
select *
from cte;

是一個 db<>fiddle。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM