Re: Subquery to select max(date) value

From: Ken Tanzer <ken(dot)tanzer(at)gmail(dot)com>
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-28 23:05:04
Message-ID: CAD3a31XUSSHcJbYSQPYeDVxyEoNtp=MYN-qrvo6tCq7Wwezi0g@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Mar 28, 2019 at 3:59 PM Rich Shepard <rshepard(at)appl-ecosys(dot)com>
wrote:

>
> After working with this query I modified it slightly to return only the
> next_contact date:
>
> select p.person_id, p.lname, p.fname, p.direct_phone, p.active,
> o.org_name, sq.*
> from people as p
> join organizations as o on p.org_id = o.org_id
> cross join
> lateral
> (select a.next_contact
> from activities as a
> where a.person_id = p.person_id and
> p.active='True' and
> a.next_contact is not null
> order by a.next_contact DESC
> limit 1) sq;
>
> It works wellm, but the row order is not that of a.next_contact. In fact,
> there seems to be no order in the returned set. The next_contact column is
> in the lateral sub-query. Does this make a difference? I've no idea how to
> modify the query so that returned rows are in decreasing next_contact
> order.
>
> Best regards,
>
> Rich
>
> You need the ORDER BY in the outer join. (And I don't think the one
inside the lateral join is doing you any good). Try:

...
a.next_contact is not null
limit 1) sq
order by sq.next_contact DESC;

Cheers,
Ken

--
AGENCY Software
A Free Software data system
By and for non-profits
*http://agency-software.org/ <http://agency-software.org/>*
*https://demo.agency-software.org/client
<https://demo.agency-software.org/client>*
ken(dot)tanzer(at)agency-software(dot)org
(253) 245-3801

Subscribe to the mailing list
<agency-general-request(at)lists(dot)sourceforge(dot)net?body=subscribe> to
learn more about AGENCY or
follow the discussion.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message David G. Johnston 2019-03-28 23:05:59 Re: Subquery to select max(date) value
Previous Message Rich Shepard 2019-03-28 22:59:11 Re: Subquery to select max(date) value