问题
The matrix's odd rows contain strings, representing integer numbers. The even rows contain strings, representing dates in mm/dd/yyyy format. The order is not guaranteed, it could be the other way around if someone changed the category names.
The grand total row has to be added to this matrix, but the following expressions throw an #Error:
=Sum(Iif(IsDate(Fields!Data.Value), 0, CInt(Fields!Data.Value)))
=Sum(Iif(InStr(Fields!Data.Value, "/"), 0, CInt(Fields!Data.Value)))
Converting 0 and field value to some other numeric data types did not work too.
Interesting enough, the expressions partially work for the grand total column, i.e. they calculate the numbers' row total, but #Error on the dates rows.
Protecting the row grand total as follows did not help either:
=Iif(Fields!Results.Value = "# of items", CStr(Sum(CInt(Fields!Data.Value))), "")
What is the correct way to implement data driven conditional totals? I could do this in plain SQL and dump into a tablix in a heartbeat but this has to be wrapped in SSRS and used with an existing matrix which must not be changed otherwise.
回答1:
The #ERROR
you get on the date rows is due to the CInt
conversion failing.
This is because IIF
is a function, not a language construct so both the true and false parameters get evaluated before being passed to the function regardless of the value of the boolean condition parameter. This means that:
=Sum(Iif(IsDate(Fields!Data.Value), 0, CInt(Fields!Data.Value)))
will always attempt the conversion to integer regardless of the result of the IsDate
function.
Try using Val
instead of CInt
. The problem with CInt
is it errors when the string to be converted is an inappropriate form; Val
doesn't have that problem - it simply grabs whatever numbers it can. So you can use the expression:
=Sum(Iif(IsDate(Fields!Data.Value), 0, Val(Fields!Data.Value)))
and then simply format it like an integer.
Note that the Val
function is still being run even when the field is not numeric but this expression succeeds because the Val
function doesn't raise errors like Cint
. We simply make the calculation and discard the result when the field is a date.
回答2:
This expression, combining the tips from both answers with additional protection, works:
=Iif(
IsNumeric(Fields!Data.Value),
Sum(Val(Iif(InStr(Fields!Data.Value, "/"), "", Fields!Data.Value))),
0
)
来源:https://stackoverflow.com/questions/20010221/ssrs-2008-conditional-data-driven-sum