简体   繁体   中英

Percentage of two values returning NULL

Same as yesterdays question which has been answered successfully but different problem. I have two values, 1 and 0 for which I need to calculate the percent change. Based on this website http://www.percent-change.com/index.php?y1=1&y2=0 the percent change between 1 and 0 is -100%. Based on the suggested formula which is (((y2- y1))/ y1) my code looks like this.

DefinedYearVSPriorYearIndividual = ((( CTEDefinedYear.IndividualCases - CTEPreviousYear.IndividualCasesLastYear ))
                                              / ( CTEPreviousYear.IndividualCasesLastYear ) ) * 100

which returns NULL.

The two numbers are

CTEDefinedYear.IndividualCases = 1
CTEPreviousYear.IndividualCasesLastYear = 0

The desired result should be -100%.

Can anybody see what I'm doing wrong?

Here is the answer.

Declare @y1 as int =1; 
Declare @y2 as int =0;
 select (((@y2- @y1))/ @y1)*100

Output is -100. You missed the *100 part.

In your case, You switched variables. attached formula is right one.

select ((0 - 1) / 1)*100;

But you used select ((1 - 0) / 0)*100;

so, you will get an error:

Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.

You have to handle 0 in the division side, with CASE logic, to avoid divide by zero error.

DECLARE @CTEDefinedYear_IndividualCases INT = 1
DECLARE @CTEPreviousYear_IndividualCasesLastYear INT = 0

SELECT ((@CTEDefinedYear_IndividualCases - @CTEPreviousYear_IndividualCasesLastYear) / (CASE WHEN @CTEPreviousYear_IndividualCasesLastYear = 0 THEN 1 ELSE @CTEPreviousYear_IndividualCasesLastYear END)) * 100

Got it to work with this code.

DefinedYearVSPriorYearIndividual =  ISNULL(100.0 * 
                                        (ISNULL(CTEDefinedYear.IndividualCases,0) 
                                        - ISNULL(CTEPreviousYear.IndividualCasesLastYear,0)) 
                                        / NULLIF(CTEPreviousYear.IndividualCasesLastYear,0),0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM