【发布时间】:2010-12-28 22:38:57
【问题描述】:
是否可以计算一列数据的均值、中位数、众数、标准差等?
一般来说,是否可以在 SQL Server Reporting Services 中进行此类数学计算?
如果可以,怎么办?
【问题讨论】:
标签: sql-server ssrs-2008
是否可以计算一列数据的均值、中位数、众数、标准差等?
一般来说,是否可以在 SQL Server Reporting Services 中进行此类数学计算?
如果可以,怎么办?
【问题讨论】:
标签: sql-server ssrs-2008
扩展@Homer 的答案,下面的代码可用于获取中位数和众数。我需要整数,但接受 Decimal 或 Double 会很快。
Dim values As New System.Collections.Generic.List(Of Integer)
Dim valueCounts As New System.Collections.Generic.Dictionary(Of Integer, Integer)
Function AddValue(newValue As Integer) As Integer
values.Add(newValue)
AddValue = newValue
If Not valueCounts.ContainsKey(newValue) Then
valueCounts.item(newValue) = 1
Else
valueCounts.item(newValue) += 1
End If
End Function
Function GetMedian() As Double
Dim count As Integer = values.Count
If count = 0 Then
Return 0
Else
values.Sort()
If count Mod 2 = 1 Then
Return values(CInt((count / 2) - 0.5))
Else
Dim index1 As Integer = count \ 2
Dim index2 As Integer = index1 - 1
Dim value1, value2 As Integer
value1 = values(index1)
value2 = values(index2)
Return (value1 + value2) / 2
End If
End If
End Function
Function GetMode() As String
Dim max As Integer = 0
For Each v As Integer In valueCounts.Values
If v > max Then
max = v
End If
Next v
Dim maxCount As Integer = 0
Dim retValue As String = ""
For Each vcKvp As System.Collections.Generic.KeyValuePair(Of Integer, Integer) In valueCounts
If vcKvp.Value = max Then
maxCount += 1
If Not String.IsNullOrEmpty(retValue) Then
retValue &= ", "
End If
retValue &= vcKvp.Key
End If
Next vcKvp
If maxCount = valueCounts.Count Then
Return "N/A"
End If
Return retValue
End Function
【讨论】:
这是我如何获得“年龄模式”:
Declare @Temp Table(Id Int Identity(1,1), Data Decimal(10,5))
Insert into @Temp Select DATEDIFF (YY, EmployeeCustomTabFields.CustDOB, GETDATE()) -
Case When (MONTH(EmployeeCustomTabFields.CustDOB)=MONTH(GETDATE()) AND DAY(EmployeeCustomTabFields.CustDOB) > DAY(GETDATE()) OR MONTH (EmployeeCustomTabFields.CustDOB) > MONTH (GETDATE()))
Then 1 Else 0 End as Age
From EM
inner join EmployeeCustomTabFields on EmployeeCustomTabFields.Employee = EM.Employee
Where EmployeeCustomTabFields.CustDepartment = '23 - Piping Design' and EM.Status = 'A' and EM.Type in ('A','B','C')
Select Top 1 with ties DATA
From @Temp
Where DATA IS Not NULL
Group By DATA
Order By COUNT(*) DESC
【讨论】:
这里是Median() 来自Report Design Tips and Tricks...
场景 1
1:在报表设计器中,打开报表属性对话框并单击代码选项卡。定义一个数组,一个接受一个值并将其添加到数组中的函数,以及一个计算数组中值的函数;
Dim values As New SystemCollections.ArrayList
Function AddValue(newValue As Decimal) As Decimal
values.Add(newValue)
AddValue = newValue
End Function
Function GetMedian() As Decimal
Dim count As Integer = values.Count
If (count > 0)
values.Sort()
GetMedian = values(count\2)
End If
End Function
2:将对函数的调用包装在一个聚合中,并将其添加到详细信息行中的表达式中。
=Max(Code.AddValue(Fields!field.Name))
3:从表尾的文本框中,调用 GetMedian() 以检索值
=Code.GetMedian()
【讨论】:
System.Collections.ArrayList