How to calculate Running Multiplication

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

I have two tables

WAC table

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


        
4条回答
  •  有刺的猬
    2020-12-16 18:49

    For the sake of completeness here is a full solution for SQL Server 2012 that uses the EXP(SUM(LOG(val))) trick suggested by @usr in another answer.

    WITH
    CTE
    AS
    (
        SELECT
            0 AS ID
            ,item
            ,baseline AS wac_inc
            ,baseline AS m
        FROM baseline
    
        UNION ALL
    
        SELECT
            ID
            ,item
            ,wac_inc
            ,1 + wac_inc/100 AS m
        FROM wac
    )
    SELECT
        ID
        ,item
        ,wac_inc
        ,m
        ,EXP(SUM(LOG(m)) OVER (PARTITION BY item ORDER BY ID ROWS UNBOUNDED PRECEDING)) AS MulRows
    FROM CTE;
    

    result set

    ID  item wac_inc            m                   MulRows
    0   A   10.000000000000000  10.000000000000000  10
    1   A   2.310000000000000   1.023100000000000   10.231
    2   A   1.100000000000000   1.011000000000000   10.343541
    3   A   2.130000000000000   1.021300000000000   10.5638584233
    4   A   1.340000000000000   1.013400000000000   10.7054141261722
    

    If SQL Server 2012 is available, this window SUM is very efficient. For previous versions any set-based solution would result in O(n*n) complexity, which means that cursor would be a better way. Here is a very good article by Aaron Bertrand comparing different methods of calculating running totals: http://sqlperformance.com/2012/07/t-sql-queries/running-totals Or SO question: Calculate running total / running balance

    Of course, if your table is small, then set-based solution with O(n*n) complexity may run faster than O(n) solution with the cursor due to cursor overhead, so you need to check the performance with your real data.

提交回复
热议问题