Re: Selecting records with highest timestamp - for a join

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Alexander Farber <alexander(dot)farber(at)gmail(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Selecting records with highest timestamp - for a join
Date: 2016-10-19 21:33:13
Message-ID: CAKFQuwbBx1F0cLOW5tZ1EDeQA7F3pDgd8+vSyu5aNmNptF8aUA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, Oct 19, 2016 at 11:35 AM, Alexander Farber <
alexander(dot)farber(at)gmail(dot)com> wrote:

> I.e. a user can have several records in the above table, but I always use
> the most recent one (the one with the highest "stamp") to display that user
> in my game.
>

​And if the second most recent has a picture but the most recent one does
not? Do you want to accept the missing value because its on a more recent
record or do you want to take the most recent non-missing value?

​Assuming "most recent not missing" and given:

PRIMARY KEY(sid, social)

​You basically want:

SELECT s_id, first_nonnull(photo ORDER BY stamp DESC, social)
FROM ...
GROUP BY s_id

You need to write a custom first_nonnull function that ignores NULL and a
custom aggregate to go along with it. Examples abound on the Internet.

Note that the Window function first_value doesn't quite do this...you want
to constrain the result to be non-null unless all candidate values are null
(or there are none).

If you have a unique index on (sid, stamp) you could solve the alternative
problem with a simple (sid, max(timestamptz) join back against the social
table.

David J.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Jonathan Eastgate 2016-10-20 08:03:03 Sequences / Replication
Previous Message Adrian Klaver 2016-10-19 20:58:30 Re: Selecting records with highest timestamp - for a join