September 10, 2003 at 9:12 am
This should be an easy one for the pros in here. Bear with me, I'm still learning the ropes:
If I have a field called "AGE" which allows for nulls, and I attempt to do an average on this column, how are the null values handled? Are they factored into the average as zeros, or just ignored?
Thanks for the help!
September 10, 2003 at 9:31 am
you can try
avg(isnull(age,0))
September 10, 2003 at 9:50 am
Well I don't want to assign a value of zero to it, I just want to ignore it if it is null. Does AVG does that by default?
September 10, 2003 at 10:54 am
The AVG function will ignore NULL values in its calculation and provide a warning that NULL value is eliminated. You could test it easily.
September 10, 2003 at 11:05 am
That's all I needed to know! Thanks!
September 11, 2003 at 12:36 am
quote:
The AVG function will ignore NULL values in its calculation and provide a warning that NULL value is eliminated. You could test it easily.
that's right.
In addition, you know, that taking your average this way might more or less vary from the 'real' average. I mean one pitfall might be something like the following pseudoSQL code
AVG(age) / COUNT (All_Data).
To be (more) precise you should use
AVG(age) / COUNT (age is not null)
Just my $0.02 cents anyway
Frank
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
September 11, 2003 at 1:42 am
Stupid, stupid Frank
Forget my last post.
AVG already does this for you!
Frank
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
September 11, 2003 at 5:00 am
But look at the following:
CREATE TABLE #UserNameAge (
UserName varchar (50) NOT NULL ,
Age int NULL
) ON [PRIMARY]
INSERT INTO #UserNameAge(UserName, Age) VALUES ('Andy', 30)
INSERT INTO #UserNameAge(UserName, Age) VALUES ('Brad', NULL)
INSERT INTO #UserNameAge(UserName, Age) VALUES ('Chet', 30)
SELECT AVG(Age) FROM #UserNameAge-- result = 30
SELECT SUM(Age)/COUNT(Age) FROM #UserNameAge-- result = 30
SELECT SUM(Age)/COUNT(*) FROM #UserNameAge-- result = 20
DROP TABLE #UserNameAge
Domain aggregate functions (SUM, AVG, COUNT etc) ignore nulls except for COUNT which will include nulls if you use the COUNT(*) syntax instead of COUNT(<column>) syntax.
September 11, 2003 at 5:19 am
quote:
Domain aggregate functions (SUM, AVG, COUNT etc) ignore nulls except for COUNT which will include nulls if you use the COUNT(*) syntax instead of COUNT(<column>) syntax.
yes, I already crucified myself
Frank
Wenn Englisch zu schwierig ist?
--
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply