Re: Filling null values

From: "David Johnston" <polobo(at)yahoo(dot)com>
To: "'jeffrey'" <johjeffrey(at)hotmail(dot)com>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: Filling null values
Date: 2011-08-05 17:22:59
Message-ID: 004501cc5394$537a9730$fa6fc590$@yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

-----Original Message-----
From: pgsql-general-owner(at)postgresql(dot)org
[mailto:pgsql-general-owner(at)postgresql(dot)org] On Behalf Of jeffrey
Sent: Friday, August 05, 2011 12:33 PM
To: pgsql-general(at)postgresql(dot)org
Subject: [GENERAL] Filling null values

I have a table that looks like this:

homeid city date measurement pre/post
123 san francisco 1/2/2003 1458 pre
123 san francisco NULL 1932 post
124 los angeles 2/4/2005 938 pre
124 NULL NULL 266 pre
124 los angeles 7/4/2006 777 post

I'd like to write a query so that I get the following result:

homeid city date measurement pre/post
123 san francisco 1/2/2003 1458 pre
123 san francisco 1/2/2003 1932 post
124 los angeles 2/4/2005 938 pre
124 los angeles 2/4/2005 266 pre
124 los angeles 7/4/2006 777 post

If a city or date is null, then it will fill from other not null values with
the same homeid. If given the choice, it will preferentially fill from a
row where homeid AND pre/post match. But if that doesn't match, then it
will still fill from the same homeid.

Does anyone have ideas for this?

---------------------------------------------------------------
What version are you using? You may be able to accomplish your goals with
Window functions.

If "homeid" determines "city" you should just remove "city" from the table
altogether and create a lookup table where "homeid" is the PK and "city" is
one of the other columns. Your date issue is somewhat more problematic to
correctly address.

As an alternative to Window functions you'd probably want to, generally,
create lookup tables. I just described the "homeid" lookup table but the
date lookup table is a little more complicated. The general idea would be
to ORDER and NUMBER the current records and then create a master lookup
using ROW_NUMBER, "homeid", and "date". Then, for any rows missing a date
you point into the lookup table and use the date from the lookup record with
the largest ROW_NUMBER less than the current row.

David J.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Andrew Sullivan 2011-08-05 17:53:42 Re: Temp table visibility
Previous Message jeffrey 2011-08-05 16:32:47 Filling null values