Re: Mathematical operations with NULL values

From: Richard Huxton <dev(at)archonet(dot)com>
To: Alexander Pucher <pucher(at)atlas(dot)gis(dot)univie(dot)ac(dot)at>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Mathematical operations with NULL values
Date: 2004-10-15 10:23:06
Message-ID: 416FA50A.7030900@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Alexander Pucher wrote:
> Hi,
>
> given a table with some data, e.g. some monthly measures. Some of the
> measures are missing though.
>
>
> id m1 m2 m3 m4 m5 .... m12
> ----------------------------------------------
>
> 1 23 45 66 76 76 .... 12 2 76 NULL 77
> 88 77 ... 89
> 3 67 87 98 NULL 78 ... NULL
>
> I would like the calculate the yearly average of each row, something
> like ((m1+m2+m3+m4+m5+...m12)/12). This would work if I had all montly
> values for one year. In the case of at least one NULL value involved, I
> would get NULL as result.
>
> So instead of dividing each year by 12, I would have to divide by the
> number of measures available in each row.

The "correct answer" is to structure your data differently. If you had a
table:
measures (id, month_num, measurement)
you could then use:
SELECT id, AVG(measurement) FROM measures GROUP BY id
You don't even need nulls any more, just don't record values for those
months you don't know about.

If you can't restructure your table, you'll need to write a procedure
that checks each value in turn for null-ness and calculates accordingly.

--
Richard Huxton
Archonet Ltd

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Barry S 2004-10-15 11:16:38 Re: Change query priority
Previous Message Oleg Bartunov 2004-10-15 09:57:08 Re: Tsearch2 trigger firing...