使用多列输入的累积乘积

时间:2020-10-13 11:17:55

标签: sql sql-server

我结合了一些每日收益估算和每周发布的月度(MTD)收益。我想将这两个数据系列结合起来以获得每日的MTD估算值。

我试图在下面总结我想存档的内容

enter image description here

我得到了除MTD_estimate之外的所有列,我想从DailyReturnEstimate和MTD派生这些列。如果存在MTD值,则应使用该值。否则,它应该做收益的累加积。我的代码如下

select *, exp(sum(log(1+DailyReturnEstimate)) OVER (ORDER BY dates) )-1 as Cumu_DailyReturn from TestTbl

我的问题是,我不确定在做累积乘积时如何使用MTD值。

我正在使用Microsot SQL2012。我在下面做了一个小数据示例:

CREATE TABLE TestTbl (
  id integer PRIMARY KEY,
  dates date,
  DailyReturnEstimate float,
  MTD integer,
);

INSERT INTO TestTbl
(id, Dates, DailyReturnEstimate, MTD) VALUES
(1, '2020-01-01', -0.01, NULL  ),
(2, '2020-01-02', 0.005 , NULL  ),
(3, '2020-01-03', 0.012 , NULL  ),
(4, '2020-01-04', -0.007 , NULL ),
(5, '2020-01-05', 0.021 , 0.016  ),
(6, '2020-01-06', 0.001 , NULL  ); 

1 个答案:

答案 0 :(得分:1)

这有点棘手,但是我们的想法是根据已经定义mtd的位置设置单独的组。然后仅在这些组中进行计算:

select t.*,
       exp(sum(log(1+coalesce(mtd, DailyReturnEstimate))) OVER (partition by grp ORDER BY dates) )-1 as Cumu_DailyReturn
from (select t.*,
             count(mtd) over (order by dates) as grp
      from testtbl t
     ) t;

Here是db <>小提琴。