Re: Subquery to select max(date) value [RESOLVED] - Mailing list pgsql-general

From Rich Shepard
Subject Re: Subquery to select max(date) value [RESOLVED]
Date
Msg-id alpine.LNX.2.20.1903290714540.12288@salmo.appl-ecosys.com
Whole thread Raw
In response to Re: Subquery to select max(date) value  (Andrew Gierth <andrew@tao11.riddles.org.uk>)
List pgsql-general
On Fri, 29 Mar 2019, Andrew Gierth wrote:

> 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,

User error: I had a couple of date typos (2018 rather than 2019) and was
thinking of generating the display in ascending, rather than decending,
order.

Thinking again about what I need in terms of query results I made a couple
of changes. Now the query selects the most recent next_contact date >= a
week ago today and into the future:

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 >= current_date - interval '7' day and
              a.next_contact is not null
          order by a.next_contact ASC
          limit 1) sq
          order by sq.next_contact ASC;

The results are what I need and allow me to not miss a date as long as I run
the query at least once a week.

My thanks to you, David J., and Ken for the valuable lessons.

Best regards,

Rich



pgsql-general by date:

Previous
From: Prakash Ramakrishnan
Date:
Subject: Re: plctl extension issue postgresql 11.2
Next
From: Durgamahesh Manne
Date:
Subject: Regarding pgaudit log_directory