1

I am trying to work out the SQL to average a series of numbers, but only to include those greater than 0.

For example:

Field
4
5
0
6

SELECT Avg(Field) FROM Table;

gives 3.75. But I want it to ignore the 0 so the average is 5.

SELECT Avg(Field) FROM Table where Field > 0;

works but what if I have more than 1 field:

Field1   Field2
4        2 
5        0
0        3
6        4

SELECT Avg(Field1), Avg(Field2) FROM Table;

Using

SELECT Avg(Field1), Avg(Field2) FROM Table where Field1 >0 and Field2>0;

will not work

How do I do that? Note the numbers can be anything from 0 to 100

2
  • Will the fields always have same value? I mean: will Field1 be always 0 or 5? or it may be 0, 1, 2, 123 etc? Commented Mar 13, 2015 at 17:52
  • No - the numbers could be anything from 0 to 100 Commented Mar 13, 2015 at 17:53

5 Answers 5

3

Just filter out 0 using the where clause.

SELECT Avg(Field) FROM Table Where Field > 0
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - can you see the supplementary. I was trying to keep the question simple.
@RichardGriffiths jpw beat me to that! :)
1

You can use a conditional expression:

SELECT 
  Avg(case when Field1 > 0 then Field1 end), 
  Avg(case when Field2 > 0 then Field2 end) 
FROM table

1 Comment

Perfect - I have not come across that before. Thank you very much.
0
SELECT Avg(Field) FROM yourtable where Field > 0    ;

1 Comment

Thanks - can you see the supplementary. I was trying to keep the question simple.
0

You will have to fake AVG() :):):)

SELECT SUM(Field1)/SUM(IF(field1>0, 1, 0)), SUM(Field2)/SUM(IF(field2>0, 1, 0))

I assume there is GROUP BY in the query

Comments

0

Convert the 0 to null like this:

SELECT AVG(IF(N=0,NULL,N)) FROM
(
SELECT 5 N
UNION ALL SELECT 4 
UNION ALL SELECT 0 
UNION ALL SELECT 2

) the_ns

1 Comment

That could work but I was trying to keep the question simple. They are not just 5s.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.