Вопрос

I have a field in my report that shows the percentage of difference between two other columns A and B. Columns A and B are integer values and can each be positive, negative, or zero. I need to be able to provide a positive, negative, or zero % change based on the difference between A and B.

I understand (and have used many times) the usual method as posted all over StackOverflow for avoiding division by zero error in SSRS:

=IIF(Fields!A.Value=0,0,Fields!B.Value-Fields!A.Value/IIF(Fields!A.Value=0,1,Fields!A.Value))

However in this case the usual method is insufficient. Consider the following:

 A   |   B   |   Diff   |   % Change        |  % Change
                         (By Usual Method)   (As I need to see it)
 2   |   3   |    1     |     50%           |     50%
-1   |   2   |    3     |     -300%         |     300%
 0   |   0   |    0     |     0%            |     0%
 0   |   3   |    3     |     0%            |     100%
 0   |  -3   |   -3     |     0%            |    -100%

I need an expression that will avoid the divide by zero error, but I cannot simply replace the error message with 0%. Any help the community can provide would be greatly appreciated!

Это было полезно?

Решение

Based on the % change you want to see, you'll need to do something slightly different whenever A=0 or A<0. So, using your examples of A for original value and B for the new value: if A is 0 determine if your % change should be 0 or +/-100 based on the value of B. If A is not 0, handle negative values of A by taking the absolute value in the denominator; otherwise use the normal % change formula:

=IIF(Fields!A.Value=0, 
IIF(Fields!B.Value=0, 0, Fields!B.Value/Abs(Fields!B.Value)), 
IIF(Fields!A.Value<0, (Fields!B.Value-Fields!A.Value)/Abs(Fields!A.Value), (Fields!B.Value-Fields!A.Value)/Fields!A.Value))

Seems to work for your provided values and for a few others I made up:

SSRS Example

Другие советы

How about a null? I am assuming you are stuck on using a format of "P0" the below will work but will not yield a "%" sign.

IIF(Fields!Denominator.Value=0 OR IsNothing(Fields!Denominator.Value),"",(Fields!Numerator.Value / Fields!Denominator.Value) * 100)

Starting from @Irb 's incomplete solution: This will provide a null value when demoninator is zero

=IIF(Fields!Denominator.Value=0,
Nothing,
Fields!Numerator.Value/IIF(Fields!Denominator.Value=0,1,Fields!Denominator.Value))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top