The SQL Server VARP Function calculates the Statistical Variance for the population of total rows selected by the SELECT Statement. The syntax of the VARP Function is
SELECT VARP([Column_Name]) FROM [Source]
SQL Server VARP Function only works on Numeric Columns, and it ignores Nulls. The math formulas behind the VARP function to calculate the Statistical Variance for the population are 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
For this VARP Function, We use the below shown data.
SQL VARP Example
It returns the Variance for the population of the total number of records present in the specified column. For example, the following SQL Server query will calculate the variance of total records present in the [Yearly Income] column from the 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 products belonging to a particular category. In these situations, we use the GROUP BY Clause to group the products by category. And then, use this Function to calculate the variance for the population of products present in each group. Let us see the Aggregate Function Example
SELECT [Occupation] ,VARP([YearlyIncome]) AS [Income Variance] FROM [Customer] GROUP BY [Occupation]
The above SQL Select Statement Query will find, the Customers associated with the particular Department and calculate their income variance
We are taking the 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
VARP In Having Clause
When we are grouping the data, In some cases, we usually check for the conditions against the aggregated data. In these circumstances, we use the SQL HAVING Clause along with Group By Statement. For instance, the following query groups the Customers by their Occupation and then finds the Income variance of each group.
SELECT [Occupation] ,VARP([YearlyIncome]) AS [Income Variance] FROM [Customer] GROUP BY [Occupation] HAVING VARP ([YearlyIncome]) > 0
The below lines of code will check whether the aggregated amount (Variance for the population of Yearly income for each Group) is greater than 0 or not. If this is True, then the corresponding records are displayed.
HAVING VARP([YearlyIncome]) > 0