用于累积乘法和求和的SQL查询

时间:2017-12-15 14:02:55

标签: sql

我正在尝试实现以下操纵的累计和

enter image description here

编写了以下SQL,但是查询的这一部分需要更正  ELSE(Exp(Sum(Log(Abs(NULLIF(总,0)))))+值) 因为没有考虑+值位来考虑连续聚合。

感谢您的帮助!!

with DTA AS
(
select *,  case when id = 1  then  value*Multiplier  else  Abs(NULLIF(Multiplier,0))  end as total from testTable
)
,
DTB AS (
SELECT id,value,Multiplier,total,
(SELECT 
       CASE              
                 WHEN B.id = 1 THEN CONVERT(decimal(18,5), B.total)                                              
                 ELSE ( Exp(Sum(Log(Abs(NULLIF( total  , 0))))) +value ) 
               END
        FROM   DTA a 
        WHERE  B.id >= A.id) as  cumulativeSum

FROM   DTA B
)

select * from DTB order by id asc

2 个答案:

答案 0 :(得分:1)

你可以这样做:

select tt.*,
       exp(sum(log(nullif(abs(value * multiplier), 0))) over (order by id)) as cumulativeProduct
from testTable tt;

答案 1 :(得分:0)

通过C#添加自定义聚合函数并在SQL Server中注册dll来解决它。

参考:Custom Aggregates in SQL Server