sql-server - SQL Server 渐进/复合减法?

标签 sql-server group-by aggregate-functions cumulative-sum

我有一个如下所示的表格。我试图弄清楚如何使用“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/

相关文章:

sql - PostgreSQL 中具有多个输入列的用户定义聚合函数

mysql - 使用连接、分组依据和聚合函数的 SQL 选择查询

mysql - SQL计数聚合函数和子查询

sql-server - WITH NOCHECK CHECK CONTRAINT和CHECK CONSTRAINT之间的区别

sql-server - Sql Server 2005 身份列上的主键冲突

postgresql如何分组然后得到first_time和last_time,

python - pandas groupby 并在每组以 1 开头的组内排名

mysql - 如何汇总多个表的行大小

sql-server - 我如何检查sql server 'views'依赖关系

sql-server - 存储过程中的经典 ADO 和表值参数