SQL Server Admin
T-SQL Articles

June 21, 2011

Standard Deviation in SQL Server and Aggregation on Aggregates




SQL Server makes calculation of Standard Deviation relatively easy with the STDEV statistical aggregate function. What I learnt recently was that you can either apply this function to all values or can even select distinct values. You can also perform an aggregation on aggregates that can be used in reports.
I was facing one such requirement where aggregates were to be calculated and we had to consider distinct values as well while calculating standard deviation. Here’s a sample example using the Northwind database. 
SELECT
SUM(Freight) as [Total Freight],
AVG(Freight) as [Average Freight],
STDEV(ALL Freight) as [Freight Deviation],
STDEV(DISTINCT Freight) as [Distinct Freight]
FROM Orders
WHERE ShipCountry = 'UK'


As you can see, we are using the ‘ALL’ and ‘DISTINCT’ to specify all or distinct values respectively.

SQL Server Standard Deviation

If you are creating reports using SSRS, you can create expressions performing aggregation on aggregates. Here’s an example:

=StDev(Sum(Fields!Products.Price))

The StDevP function is also similar except that it performs statistical standard deviation for  all values in the specified expression, it evaluates the ‘entire’ data population. The StDev on the other hand is based on a sample of the data population.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

0 Responses to "Standard Deviation in SQL Server and Aggregation on Aggregates"
 

Copyright © 2009-2012 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions