SSRS 2008 Conditional data driven sum

為{幸葍}努か 提交于 2020-01-25 18:05:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!