SSRS - Median by Group - Jagged Array?

筅森魡賤 提交于 2019-12-11 16:53:32

问题


I'm faced with a challenge in two parts. I've been requested to replace 3 columns in a Matrix that aggregates on Name in the row group. The 3 columns are outside of the Column group.

Challenge 1 - Matrices want to summarize the Data pane. There seems to be no way to show the Raw Data (and then hide it, in order for these rows during runtime to populate an array).

Challenge 2 - I need to calculate the median BY name. This means either, during runtime, I need to calculate one median for each name at a time, reset the array, and start fresh for the next name value, OR, I need a multi-dimensional array where each ordinal is itself an array corresponding to a name.

I'm also a total code monkey at VB.

Here's what I've currently borrowed from an online post about calculating Median in SSRS.

    Dim values As System.Collections.ArrayList

    Function AddValue(ByVal newValue As Decimal)
        If (values Is Nothing) Then
            values = New System.Collections.ArrayList()
        End If
        values.Add(newValue)
    End Function

    Function GetMedian() As Decimal
        Dim count As Integer = values.Count
        If (count > 0) Then
            values.Sort()
            GetMedian = values(count / 2)
        End If
    End Function

回答1:


I think I have a SQL solution that doesn't utilize a loop.

;WITH Counts AS
(
   SELECT SalesPerson, c = COUNT(*)
   FROM dbo.Sales
   GROUP BY SalesPerson
)
SELECT a.SalesPerson, Median = AVG(0.+Amount)
FROM Counts a
CROSS APPLY
(
   SELECT TOP (((a.c - 1) / 2) + (1 + (1 - a.c % 2)))
      b.Amount, r = ROW_NUMBER() OVER (ORDER BY b.Amount)
   FROM dbo.Sales b
   WHERE a.SalesPerson = b.SalesPerson
   ORDER BY b.Amount
) p
WHERE r BETWEEN ((a.c - 1) / 2) + 1 AND (((a.c - 1) / 2) + (1 + (1 - a.c % 2)))
GROUP BY a.SalesPerson;


来源:https://stackoverflow.com/questions/29947709/ssrs-median-by-group-jagged-array

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