How to calculate Running Multiplication

后端 未结 4 1651
逝去的感伤
逝去的感伤 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:46

    you could do it easily with a recursive cte:

    with rec(id ,wi,i,r) as 
    (
      select top (1) w.ID,w.wac_inc,w.item, b.baseline * (1 + (w.wac_inc/100))
      from wac w join baseline b on w.item=b.item
      union all
      select w.ID,w.wac_inc,w.item, r.r * (1 + (w.wac_inc/100))
      from wac w
      join rec r on (w.ID)-1 = r.id
     )
     select * from rec
    

    Output:

    1   2.31    A   10.231
    2   1.1     A   10.343541
    3   2.13    A   10.563858
    4   1.34    A   10.705414
    

    check in the demo


    EDIT - Adding another solution:

    you can do it by taking help from a copy of your original table :

    Assuming your schema and data is:

    create  table wac
      (ID int,wac_inc numeric(38,15),item char )
    
    insert wac
    values (1,2.31,'A'),
    (2,1.1,'A'),
    (3,2.13,'A'),
    (4,1.34,'A')
    

    1.take a copy from original table(use a temp table or a table variable) and update the first record from baseline table:

    create table  #tmp (ID int,wac_inc numeric(38,15),item char, Running_Mul numeric(38,15))
    insert into #tmp select id,wac_inc,item,null from wac
    
    update #tmp set Running_Mul = (select top 1 baseline from baseline)*(1+(wac_inc/100))
    where id = (select min(id) from #tmp)
    

    2.declare these variables:

    declare @id int,@rm numeric(38,15)
    select @id=min(id) from #tmp
    
    select @rm=Running_Mul from #tmp where id=@id
    

    3.update the copy:

    update #tmp
    set @rm=Running_Mul= case 
                        when @id <> id then @rm*(1+(wac_inc/100))
                        else Running_Mul
                     end,
    @id=id
    

    and now you can check the result:

    select * from #tmp
    drop table #tmp
    

    Result:

    ID  wac_inc             item    Running_Mul
    1   2.310000000000000   A   10.231000000000000
    2   1.100000000000000   A   10.343541000000000
    3   2.130000000000000   A   10.563858000000000
    4   1.340000000000000   A   10.705414000000000
    

提交回复
热议问题