Pergunta

I have a table that looks like the below. I am trying to figure out how to update the "endval" column with a value that is from the "startval" column, reduced by 10% for every multiple of 5 in the "effect" column.

declare @tbl table ( rowid int , effect Int , startval decimal(6,2) , endval decimal(6,2) )
insert @tbl values 
  ( 0 , 10 , 6 , null )   -- expect 4.86 in endval
, ( 1 , 40 , 10 , null  ) -- expect 4.30 in endval
, ( 2 , 7  , 1 , null ) -- expect .9 in endval
select * from @tbl

Note that rowid 2 does not have an even multiple of 5 in the "effect" column, so it is only reduced by 10% once.

I am trying to come up with any way to "progressively percentage" in TSQL (2012) and nothing is coming to mind. Help?

Thanks.

Foi útil?

Solução

Use POWER to apply the multiple percentages.

declare @tbl table ( rowid int , effect Int , startval decimal(6,2) , endval decimal(6,2) )
insert @tbl values 
      ( 0 , 10 , 6 , null )   -- expect 4.86 in endval
    , ( 1 , 40 , 10 , null  ) -- expect 4.30 in endval
    , ( 2 , 7  , 1 , null ) -- expect .9 in endval

select  rowid, startval, [endval]=power(0.90, effect/5)*startval
from    @tbl;

Results:

rowid   startval    endval
0       6.00        4.8600
1       10.00       4.3000
2       1.00        0.9000

A simple loop in a cte will also get it done:

;with cte (rowid, calc, i) as
(
    select  rowid, startval, effect/5
    from    @tbl
    union all
    select  t.rowid, cast(calc*.9 as decimal(6,2)), i-1
    from    @tbl t
    join    cte c on 
            c.rowid = t.rowid
    where   c.i > 0
)
select  * 
from    cte c
where   i = 0
order
by      rowid;

Results:

rowid   calc    i

0       4.86    0
1       4.30    0
2       0.90    0
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top