How to calculate Running Multiplication

后端 未结 4 1655
逝去的感伤
逝去的感伤 2020-12-16 18:11

I have two tables

WAC table

ID  wac_inc             item
--  -----------------   ----
1   2.310000000000000   A
2   1.10000000000000         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 18:41

    You can transform a series of multiplications into a series of additions with the following math trick:

    exp(log(a) + log(b)) = a * b
    

    So MUL(a) is EXP(SUM(LOG(a))).

    SELECT SUM(val) AS [Sum], EXP(SUM(LOG(val))) AS Product
    FROM (VALUES 
        (1), (2), (3), (4)
    ) x(val)
    

    This emits sum = 10, product = 24.

    Potential problems are rounding errors and zero factors.

    You can now use one of the usual ways to achieve a running aggregate such as windowing functions. That's a solved problem.

提交回复
热议问题