Re: Subquery to select max(date) value

From: Rich Shepard <rshepard(at)appl-ecosys(dot)com>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Subquery to select max(date) value
Date: 2019-02-15 21:33:23
Message-ID: alpine.LNX.2.20.1902151327540.31662@salmo.appl-ecosys.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Fri, 15 Feb 2019, Andrew Gierth wrote:

> LATERAL (SELECT ...) is syntactically like (SELECT ...) in that it
> comes _after_ a "," in the from-clause or after a [LEFT] JOIN keyword.

Andrew,

Yes, the missing ',' made a big difference.

> You'd want a condition here that references the "people" table;

Got it.

> and I'm guessing you want that ordered by next_contact alone, possibly
> with LIMIT 1 to get just the nearest following next_contact time.

Using LIMIT 1 produces only the first returned row. This statement (using
max() for next_contact) produces no error message, but also no results so I
killed the process after 30 seconds. Without a syntax error for guidance I
don't know how to proceed. I've not before run 'explain' on a query. Would
that be appropriate here?

select p.person_id, p.lname, p.fname, p.direct_phone, o.org_name
from people as p, organizations as o,
lateral
(select p.person_id, p.lname, p.fname, p.direct_phone, o.org_name,
max(a.next_contact)
from people as p, organizations as o, activities as a
where a.next_contact > '2018-12-31' and
a.next_contact <= 'today' and
a.next_contact is not null
group by p.person_id, o.org_name, a.next_contact
order by p.person_id, o.org_name, a.next_contact) sq;

Regards,

Rich

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Andrew Gierth 2019-02-15 21:56:46 Re: Subquery to select max(date) value
Previous Message Thomas Munro 2019-02-15 21:20:02 Re: WSL (windows subsystem on linux) users will need to turn fsync off as of 11.2