all groups > sql server programming > december 2004 >
You're in the

sql server programming

group:

avg and null values


avg and null values Hassan
12/3/2004 8:04:16 PM
sql server programming:
When you do average of a column that includes null values, does it ignore
the rows with null or does it not ? If it does not, how can we include it
...i mean if we have 5 rows with one null value, how can we avg with 4 and
also average with 5.. Thanks

RE: avg and null values Ed
12/3/2004 9:07:02 PM

Here you go
avg with 4: -- ignore null
Select avg(ColummName) from TableName

avg with 5: -- include null
select avg(a.b) from (select case when ColumnName is null then 0 else
ColumnName end as b from TableName) a

Good luck

Ed




[quoted text, click to view]
Re: avg and null values Dan Guzman
12/3/2004 10:49:08 PM
[quoted text, click to view]

NULLs are ignored.

[quoted text, click to view]

I'm not exactly sure what you want but you might experiment with the
following examples:

--exclude nulls
SELECT AVG(Col1) FROM MyTable
SELECT SUM(Col1) / COUNT(Col1) FROM MyTable

--exclude nulls from SUM but include in count
SELECT SUM(Col1) / COUNT(*) FROM MyTable

--
Hope this helps.

Dan Guzman
SQL Server MVP

[quoted text, click to view]

Re: avg and null values Mark J. McGinty
12/4/2004 1:45:40 AM
Or a variation on the theme:

SELECT AVG(COALESCE(ColummName, 0)) FROM TableName

-Mark



[quoted text, click to view]

AddThis Social Bookmark Button