Skip to content
Advertisement

How to ignore nulls in aggregate functions (AVG) when using multiple case statements

I am using SQL server to find the average of some columns, but I want to ignore any column that has a value of 0 or null

Table I am reading from:

Table

My query:

When using multiple case expressions inside the AVG() function, the column always returns NULL. What am I doing wrong?

UPDATE: As pointed out by @Gordon Linoff – this is an issue with the addition rather than the aggregate function. Can anyone suggest another way of achieving my desired result?

UPDATE: My desired result:

Advertisement

Answer

Hmmm, I think you may need to substitute 0. The issue with the addition, not the average:

If everything is 0, then use NULLIF() to ignore those rows:

However, there are no such examples in your question.

EDIT:

Do you simply want this?

This is kind of like the average of the values in the two columns where the values are not 0.

The actual average would be:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement