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

问题描述 投票:1回答:2

我试图实现以下操纵的累积总和

enter image description here

编写了以下SQL,但是这个查询位需要更正ELSE(Exp(Sum(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
sql
2个回答
1
投票

你可以这样做:

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

0
投票

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

参考:Custom Aggregates in SQL Server

© www.soinside.com 2019 - 2024. All rights reserved.