Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

T-SQL The percentage increase of a number based on dataset

I have a data set like this:

Year Percentage
1990 5.0
1991 7.0
1992 2.3

i want calculate percentage increase of a number based on this data.

for example: i have a input number => 100

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

calculated number for 100 is :

100 + 5.0% = 105

105 + 7.0% = 112.35

112.35 + 2.3% = 114.93405

Can i do this in 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

>Solution :

This can be done with entirely set-based SQL. No loops or recursion needed:

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading