Skip to content

Instantly share code, notes, and snippets.

@stephlocke
Last active November 15, 2022 05:20
Show Gist options
  • Save stephlocke/c63d3adaac3b8a437a10 to your computer and use it in GitHub Desktop.
Save stephlocke/c63d3adaac3b8a437a10 to your computer and use it in GitHub Desktop.
Custom aggregate function for use with Lookup joined datasets in SSRS
'Allows aggregation of a multilookup cell and can be configured by the user
'To use add this expression to a cell's expression window:
'=code.AggLookup([aggregate choice as string], LookupSet([Local Column], [Match Column], [Return Column], [Dataset as string]))
'
'Available aggregate choices are count, sum, min, max and avg
Function AggLookup(ByVal choice as String, ByVal items as Object)
'Ensure the LookupSet array provided is not empty
If items is Nothing then
Return Nothing
End If
'Define variables
Dim current as Decimal
Dim sum as Decimal
Dim count as Integer
Dim min as Decimal
Dim max as Decimal
Dim err as String
'Define values for variables where required
current = 0
sum = 0
count = 0
err = ""
'Calculate and set variable values
For each item as Object in items
'Calculate count
count += 1
'Check value is a number
If IsNumeric(item) then
'Set current
current = Convert.ToDecimal(item)
'Calculate sum
sum += current
'Calculate min
If min = Nothing then
min = current
End If
If Min > current then
min = current
End If
'Calculate max
If max = Nothing then
max = current
End If
If max < current then
max = current
End If
'Return NaN if value is not a number
Else
err = "NaN"
End If
Next
'Select and set output based on the user choice or choice passed by function
If err = "NaN" then
If choice = "count" then
Return count
Else
Return err
End If
Else
Select Case choice
Case "sum"
Return sum
Case "count"
Return count
Case "min"
Return min
Case "max"
Return max
Case "avg"
'Calculate the average avoiding divide by zero errors
If count > 0 then
Return sum / count
Else
Return 0
End If
End Select
End If
End Function
@Proavtor
Copy link

Nice trick! Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment