TIP: SQL VARP Function will only work on Numeric Columns and it ignores Nulls.
SQL VARP Function Formula
The mathematical formulas behind the VARP function to calculate the Statistical Variance for the population in SQL Server is as shown below:
--Calculating the Mean or Average Mean = Sum of each individual/Total number of items --Calculating the Statistical Variance Variance = ((OriginalValue – Mean)² + (OriginalValue – Mean)² +.... )/Total number of items
SQL VARP Function Syntax
The basic syntax of the SQL VARP Function in SQL Server is as shown below:
SELECT VARP ([Column_Name]) FROM [Source]
In this article we will show you, How to write VARP Function in SQL Server with example. For this, We are going to use the below shown data
SQL VARP Example
VARP() simply returns the Variance for the population of total number of records present in the specified column. For example, The following query will calculate the variance of total records present in the [Yearly Income] column from Customers table.
SELECT VARP ([YearlyIncome]) AS [Income Variance] FROM [Customer]
SQL VARP Function with Group By Clause
In most cases we usually calculate the variance of a products belongs to particular category or color etc. In these situations we use GROUP BY Clause to group the products by color or category and then use the VARP Function to calculate the variance for population of products present in each group. Let us see the Example
SELECT [Occupation] ,VARP ([YearlyIncome]) AS [Income Variance] FROM [Customer] GROUP BY [Occupation]
Above SQL Query will find, the Customers associated with the particular Department and calculates their income variance
It is too big to show the calculations for every thing so, We are taking Skilled Manual profession and show you the output.
-- Calculating Mean Mean = (60000 + 80000) / 2 Mean = 70000 --Calculating variance for Population Variance for population = ( (60000 - 70000) + (80000 - 70000) ) / 2 Variance for population = 100000000
SQL VARP Function in Having Clause
When we are grouping the data, In some cases we usually check for the conditions against the aggregated data. In these situations we use SQL HAVING Clause along with Group By Statement. For example, The following query will group the Customers by their Occupation and then finds the Income variance of each individual group.
SELECT [Occupation] ,VARP ([YearlyIncome]) AS [Income Variance] FROM [Customer] GROUP BY [Occupation] HAVING VARP ([YearlyIncome]) > 0
Below lines of code will check whether the aggregated amount (Variance for population of Yearly income for each individual Group) is greater than 0 or not. If this is True then corresponding records will be displayed.
HAVING VARP ([YearlyIncome]) > 0
Thank You for Visiting Our Blog