我有一个如下所示的表格。我试图弄清楚如何使用“startval”列中的值更新“endval”列,“effect”列中每 5 的倍数减少 10%。
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
请注意,rowid 2 在“效果”列中没有 5 的偶数倍,因此仅减少 10% 一次。
我试图想出任何在 TSQL (2012) 中“渐进百分比”的方法,但什么也没有想到。帮忙?
谢谢。
最佳答案
使用POWER
应用多个百分比。
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;
结果:
rowid startval endval
0 6.00 4.8600
1 10.00 4.3000
2 1.00 0.9000
cte 中的一个简单循环也可以完成它:
;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;
结果:
rowid calc i
0 4.86 0
1 4.30 0
2 0.90 0
关于sql-server - SQL Server 渐进/复合减法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16255144/