# SQL Server Spearman's rho function

SPEARMAN_TV

Updated: 24 May 2013

Use the table-valued function SPEARMAN_TV to calculate Spearman’s rank correlation coefficient (ρ). Spearman’s ρ is defined as Pearson’s correlation coefficient for the ranks of x- and y-values. Ranks are calculated such that tied ranks receive the average of the ranks for the rank interval populated by the tie.
Syntax
SELECT * FROM [wctStatistics].[wct].[SPEARMAN_TV](
<@x_y_Query, nvarchar(max),>)
Arguments
@x_y_Query
a T-SQL statement, as a string, that specifies the x- and y-values. The x- and y-values must be of the type float or of a type that implicitly converts to float.
Return Type
RETURNS TABLE (
[R] [float] NULL,
[P] [float] NULL,
[T] [float] NULL,
[DF] [float] NULL
)

 Column Column Description R Spearman’s rho P the p-value T the t-statistic DF the number of pairs minus 2
Remarks
·         The function is insensitive to order.
·         The function only includes pairs where x-value is NOT NULL and y-value is NOT NULL
·         Use the RANK_AVG table-valued function to see the x- and y-ranks

Examples
SELECT *
INTO #s
FROM (
SELECT 106,7 UNION ALL
SELECT 86,0 UNION ALL
SELECT 100,27 UNION ALL
SELECT 101,50 UNION ALL
SELECT 99,28 UNION ALL
SELECT 103,29 UNION ALL
SELECT 97,20 UNION ALL
SELECT 113,12 UNION ALL
SELECT 112,6 UNION ALL
SELECT 110,17
)n(x,y)

SELECT p.*
FROM wct.SPEARMAN_TV('SELECT x,y from #s') k
--This CROSS APPLY UNPIVOTS the tvf columns for formatting
CROSS APPLY(
SELECT 'P', R UNION ALL
SELECT 'R', P UNION ALL
SELECT 'T', T UNION all
SELECT 'DF', DF
)p(stat_name, stat_value)

DROP TABLE #s
This produces the following result.