Skip site navigation (1) Skip section navigation (2)

Re: avg() from multiple columns

From: "Oliver Elphick" <olly(at)lfix(dot)co(dot)uk>
To: Jason Tan <jason(at)rebel(dot)rebel(dot)net(dot)au>
Cc: Miia Uski <miia(dot)uski(dot)155(at)student(dot)lu(dot)se>, pgsql-novice(at)postgresql(dot)org
Subject: Re: avg() from multiple columns
Date: 2001-09-06 06:42:15
Message-ID: 200109060642.f866gF8s009035@linda.lfix.co.uk (view raw or flat)
Thread:
Lists: pgsql-novice
Jason Tan wrote:
  >
  >
  >If you want row by row averages try this:
  >
  >select (col1+col2+col3)/3 from table;
  >
  >If you wnat to average several columns over the whole table this seems to
  >work:
  >
  >select avg(col1+col2+col3) from table;
 
Watch out for NULL values when doing this.  x + x + NULL = NULL, not 2x

You might do better to do:

  SELECT avg(col1) + avg(col2) + avg(col3)

or

  SELECT avg(COALESCE(col1, 0) + COALESCE(col2, 0) + COALESCE(col3,0))

(the two are not equivalent).

-- 
Oliver Elphick                                Oliver(dot)Elphick(at)lfix(dot)co(dot)uk
Isle of Wight                              http://www.lfix.co.uk/oliver
PGP: 1024R/32B8FAA1: 97 EA 1D 47 72 3F 28 47  6B 7E 39 CC 56 E4 C1 47
GPG: 1024D/3E1D0C1C: CA12 09E0 E8D5 8870 5839  932A 614D 4C34 3E1D 0C1C
                 ========================================
     "Behold, I stand at the door, and knock; if any man 
      hear my voice, and open the door, I will come in to 
      him, and will sup with him, and he with me."       
                                   Revelation 3:20 



pgsql-novice by date

Next:From: Francisco ReyesDate: 2001-09-06 14:21:25
Subject: What is syntax to use \i to include files?
Previous:From: Jason TanDate: 2001-09-05 05:23:47
Subject: Re: pl/pgsql recursion/arrays (fwd)

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group