Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1gu4ro-0006eP-CD for pgsql-general@arkaria.postgresql.org; Thu, 14 Feb 2019 00:27:04 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1gu4rk-0005Xe-Rm for pgsql-general@arkaria.postgresql.org; Thu, 14 Feb 2019 00:27:00 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1gu4rk-0005XW-Es for pgsql-general@lists.postgresql.org; Thu, 14 Feb 2019 00:27:00 +0000 Received: from mail.appl-ecosys.com ([50.126.108.78]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1gu4rh-0006Aw-Gm for pgsql-general@lists.postgresql.org; Thu, 14 Feb 2019 00:26:59 +0000 Received: from salmo.appl-ecosys.com (salmo.appl-ecosys.com [192.168.55.1]) by mail.appl-ecosys.com (Postfix) with ESMTP id 2376999356 for ; Wed, 13 Feb 2019 16:26:56 -0800 (PST) Date: Wed, 13 Feb 2019 16:26:56 -0800 (PST) From: Rich Shepard To: "pgsql-generallists.postgresql.org" Subject: Re: Subquery to select max(date) value In-Reply-To: <1550101890489.14429@niwa.co.nz> Message-ID: References: <2780074d-3b87-b154-8bc6-a0f898fbdde2@openvistas.net> <7c015580-fe20-be68-076c-ded42d8bf1f1@aklaver.com> <875ztno1l6.fsf@news-spur.riddles.org.uk> <0dee994f-120d-06b6-4aea-a10060d2687c@aklaver.com>, <1550101890489.14429@niwa.co.nz> User-Agent: Alpine 2.20 (LNX 67 2015-01-07) MIME-Version: 1.0 Content-Type: text/plain; charset=US-ASCII; format=flowed List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk On Wed, 13 Feb 2019, Brent Wood wrote: > I have not really followed this thread but would not a query along the lines of > select * from activity where person_id = n and timestamp = (select > max(timestamp) from activity where person_id = n); > give the required answer ie, always return the latest result for the specified person_id?? Brent, I don't know. What does work is this statement: SELECT DISTINCT ON (person_id) person_id, next_contact FROM activities AS a WHERE a.next_contact is not null and a.next_contact <= 'today' and a.next_contact > '2018-12-31' ORDER BY person_id,next_contact; which returns these results: person_id | next_contact -----------+-------------- 1 | 2019-01-14 4 | 2019-01-14 22 | 2019-01-14 36 | 2019-01-03 37 | 2019-01-14 38 | 2019-01-21 40 | 2019-02-11 41 | 2019-02-11 42 | 2019-02-11 43 | 2019-02-11 44 | 2019-02-11 45 | 2019-02-11 46 | 2019-02-11 (13 rows) Now I'm learning how to join the people and organization table using LATERAL join(s) so the results include names and phone numbers. Thanks for the suggestion, Rich