Performing aggregate calculations on null values

  • 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!

  • you can try

    avg(isnull(age,0))

  • 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?

  • 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 all I needed to know! Thanks!

  • 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]

  • 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]

  • 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.

  • 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?

    http://www.insidesql.de

    --
    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