Search code examples
sql-servermedian

Is it possible to create a generic SP to determine Median?


I am using SQL Server 2012. I guess what I am asking is should I continue on the path of researching the ability to create a SP (or UDF, but with #Temp tables probably involved, I was thinking SP) in order to have a reusable object to determine the median?

I hope this isn't too generic of a question, and is hosed, but I have spent some time researching the ability to determine a median value. Some possible hurdles include the need to pass in a string representation of the query that will return the data that I wish to perform the median on.

Anyone attempt this in the past?


Solution

  • Here is a stored proc I use to generate some quick stats.

    Simply pass a Source, Measure and/or Filter.

    CREATE PROCEDURE [dbo].[prc-Dynamic-Stats](@Table varchar(150),@Fld varchar(50), @Filter varchar(500)) 
    
    -- Syntax: Exec [dbo].[prc-Dynamic-Stats] '[Chinrus-Series].[dbo].[DS_Treasury_Rates]','TR_Y10','Year(TR_Date)>2001' 
    
    As
    
    Begin
        Set NoCount On;
    
        Declare @SQL varchar(max) = 
        '
        ;with cteBase as (
         Select RowNr=Row_Number() over (Order By ['+@Fld+'])
               ,Measure = ['+@Fld+']
         From '+@Table+'
         Where '+case when @Filter='' then '1=1' else @Filter end+' 
        )
        Select RecordCount   = Count(*)
              ,DistinctCount = Count(Distinct A.Measure)
              ,SumTotal      = Sum(A.Measure)
              ,Minimum       = Min(A.Measure)
              ,Maximum       = Max(A.Measure)
              ,Mean          = Avg(A.Measure)
              ,Median        = Max(B.Measure)
              ,Mode          = Max(C.Measure)
              ,StdDev        = STDEV(A.Measure)
         From cteBase A
         Join (Select Measure From cteBase where RowNr=(Select Cnt=count(*) from cteBase)/2) B on 1=1
         Join (Select Top 1 Measure,Hits=count(*) From cteBase Group By Measure Order by 2 desc ) C on 1=1
        '
        Exec(@SQL)
    
    End
    

    Returns

    RecordCount DistinctCount   SumTotal    Minimum Maximum Mean    Median  Mode    StdDev
    3615        391             12311.81    0.00    5.44    3.4057  3.57    4.38    1.06400795277565