Re: Subquery to select max(date) value

From: Andrew Gierth <andrew(at)tao11(dot)riddles(dot)org(dot)uk>
To: Rich Shepard <rshepard(at)appl-ecosys(dot)com>
Cc: "pgsql-generallists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: Subquery to select max(date) value
Date: 2019-03-29 00:50:53
Message-ID: 87mulev72k.fsf@news-spur.riddles.org.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

>>>>> "Rich" == Rich Shepard <rshepard(at)appl-ecosys(dot)com> writes:

Rich> Tried this and did not do it correctly. Should there be two
Rich> 'order by', one in the sub-query, the other in the top-level
Rich> query?

Yes.

Rich> This does not return the desired order:

Rich> select p.person_id, p.lname, p.fname, p.direct_phone, p.active, o.org_name, sq.*
Rich> from people as p
Rich> join organizations as o on p.org_id = o.org_id
Rich> cross join
Rich> lateral
Rich> (select a.next_contact
Rich> from activities as a
Rich> where a.person_id = p.person_id and
Rich> p.active='True' and
Rich> a.next_contact is not null
Rich> order by a.next_contact DESC
Rich> limit 1) sq
Rich> order by sq.next_contact DESC;

That query seems correct assuming you want the result in descending
order of next_contact. How did the actual result differ from your
expectation?

--
Andrew (irc:RhodiumToad)

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message github kran 2019-03-29 04:13:31 Archival process of partition tables with filtering few rows from tables.
Previous Message David G. Johnston 2019-03-28 23:31:39 Re: Subquery to select max(date) value