【问题标题】:T-SQL The percentage increase of a number based on datasetT-SQL 基于数据集的数字增加百分比
【发布时间】:2022-01-25 13:16:55
【问题描述】:

我有一个这样的数据集:

Year Percentage
1990 5.0
1991 7.0
1992 2.3

我想根据这个数据计算一个数字的百分比增长。

例如:我有一个输入数字 => 100

100 的计算数字是:

100 + 5.0% = 105

105 + 7.0% = 112.35

112.35 + 2.3% = 114.93405

我可以在 T-Sql 中这样做吗?

CREATE function [dbo].[fn_sample] (@input decimal(29,19)) returns decimal(29,19)  as

begin

DECLARE @tmp TABLE([Year] int, [Percentage] decimal(29,19))
INSERT INTO @tmp ([Year], [Percentage]) VALUES
(1990, 5),
(1991, 7),
(1992, 2.3)

--TODO Calculate number
return @input
end

【问题讨论】:

标签: sql sql-server tsql


【解决方案1】:

这可以通过完全基于集合的 SQL 来完成。不需要循环或递归:

CREATE function [dbo].[fn_sample] (@input decimal(29,19)) returns decimal(29,19)  as
begin

    DECLARE @tmp TABLE([Year] int, [Percentage] decimal(29,19));

    INSERT INTO @tmp ([Year], [Percentage]) VALUES
    (1990, 5),
    (1991, 7),
    (1992, 2.3)
    ;

    DECLARE @output decimal(29,19) = 1.00;

    SELECT @output = EXP(SUM(LOG((100.00+Percentage)/100))) 
    FROM @tmp

    return @output;
end

【讨论】:

  • 也可以使用窗口函数来完成,以显示每行的结果。请注意,如果它变为负数,这将失败
  • @Charlieface 对,或者零或 NULL 等。您必须放入一堆控件来处理一般情况(通常不会打扰 SUM(..)),我因为这个案例太具体了,所以被遗漏了。
猜你喜欢
  • 2011-09-09
  • 2010-10-13
  • 2019-01-16
  • 2011-04-08
  • 1970-01-01
  • 2019-10-13
  • 2019-06-03
  • 1970-01-01
相关资源
最近更新 更多