简体   繁体   English

计算累积产品价值

[英]Calculate cumulative product value

I have the following database table:我有以下数据库表:

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

I would like to update the Index value using the following formula:我想使用以下公式更新索引值:

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

Expected Result: (Index to be calculated order by Date asc)预期结果:(按日期升序计算的索引)

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

How can I do this using SQL?如何使用 SQL 做到这一点? I tried the following query but getting an error:我尝试了以下查询,但出现错误:

Windowed functions cannot be used in the context of another windowed function or aggregate.窗口函数不能在另一个窗口 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

Thinking mathematically, the result that you want is equivalent to this product:从数学上思考,你想要的结果相当于这个产品:

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

where a1, a2, a3 are the values of the column [Return] .其中 a1, a2, a3 是[Return]列的值。

This product can be obtained by:该产品可以通过以下方式获得:

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

and you can do this in sql like this:您可以在 sql 中执行此操作,如下所示:

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

See the demo .请参阅演示

A recursive CTE might be the simplest approach:递归 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;

Here is a db<>fiddle. 是一个 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM