首页 > 解决方案 > Standard Deviation of a Row

问题描述

How do I find the standard deviation of a row in SQL Server? I'm trying to find the standard deviation for the image below but I'm unsure how.

Would I do STDEV on the total of the row? I'd want another column at the end showing the standard deviation for the entire year. I saw in Excel someone did =(STDEV(C4:N4)).

enter image description here

标签: sql-server

解决方案


Aggregate functions such as SUM or STDEV operate over rows.

You can use CROSS APPLY to unpivot the columns to rows to calculate an aggregate on them

SELECT t.*,
       ca.StdDev
FROM   YourTable t
       CROSS APPLY (SELECT STDEV(Val)
                    FROM   (VALUES (JANUARY),
                                   (FEBRUARY),
                                   (MARCH),
                                   (APRIL),
                                   (MAY),
                                   (JUNE),
                                   (JULY),
                                   (AUGUST),
                                   (SEPTEMBER),
                                   (OCTOBER),
                                   (NOVEMBER),
                                   (DECEMBER) ) v(Val)) ca(StdDev) 

推荐阅读