I have a table with integer values. They could be negative, 0, positive and NULL. I need treat NULL as 0, calculate average for a given date and if average value is less than 0 then put 0 there.
My query is the following:
select
Id,
ValueDate,
case
when avg(isnull(Value, 0)) > 0 then avg(isnull(Value, 0))
else 0
end AvgValue
from SomeTable
where ValueDate = @givenDate
group by Id, ValueDate
How to avoid double aggregate function definition in case statement (aggregate statement could be much more complex)?