Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average and case in SQL Server 2012

I'd like to have the average of a column when its bigger than zero.

Select Avg(Case when Column > 0 then Column else 0 end) as Avg

but I'm afraid the else clause is not correct. I want to ignore the zero values in the average.

like image 850
Ariox66 Avatar asked Jan 10 '15 08:01

Ariox66


People also ask

What is the use of AVG () function in SQL?

The AVG() function returns the average value of a numeric column.

How do you calculate average in SQL Server?

AVG () computes the average of a set of values by dividing the sum of those values by the count of nonnull values. If the sum exceeds the maximum value for the data type of the return value, AVG() will return an error.

Can you use average in SQL?

SQL Average function syntaxALL keyword enables us to calculate an average for all values of the resultset and it is used by default. The DISTINCT keyword implements the AVG() function only for unique values.


1 Answers

Remove else part from case statement so the values less than 1 will be NULL.

Null values will be eliminated by the Avg aggregate. So you will get the average of values which are greater then 0. Try this.

Select Avg(Case when [Column]>0 then [Column] end) as [Avg]

DEMO

Without else part in case statement (Expected Average)

SELECT Avg(CASE WHEN a > 0 THEN a END) [Avg]
FROM   (SELECT 2 a UNION ALL SELECT 2 UNION ALL SELECT -1) bb

Result : 2

With else part in case statement.

SELECT Avg(CASE WHEN a > 0 THEN a ELSE 0 END) [Avg]
FROM   (SELECT 2 a UNION ALL SELECT 2 UNION ALL SELECT -1) bb 

Result : 1

like image 102
Pரதீப் Avatar answered Oct 07 '22 08:10

Pரதீப்