Sunday, April 27, 2014

Find AVG : Exclude values which are 0 while finding AVG

like this ?



; with tbl
as
(
select col1 = 2, col2 = 0, col3 = 4 union all
select col1 = 2, col2 = 6, col3 = 4
)
select *,
average = (
col1 + col2 + col3
)
/ (
case when col1 <> 0 then 1 else 0 end
+ case when col2 <> 0 then 1 else 0 end
+ case when col3 <> 0 then 1 else 0 end
)
from tbl

col1 col2 col3 average
----------- ----------- ----------- -----------
2 0 4 3
2 6 4 4

(2 row(s) affected)







K H Tan


No comments:

Post a Comment