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 1gtvWR-0005l1-VM for pgsql-general@arkaria.postgresql.org; Wed, 13 Feb 2019 14:28:24 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1gtvWQ-0003kQ-JP for pgsql-general@arkaria.postgresql.org; Wed, 13 Feb 2019 14:28:22 +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 1gtvWQ-0003kH-7n for pgsql-general@lists.postgresql.org; Wed, 13 Feb 2019 14:28:22 +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 1gtvWN-0000yc-Qo for pgsql-general@lists.postgresql.org; Wed, 13 Feb 2019 14:28:20 +0000 Received: from salmo.appl-ecosys.com (salmo.appl-ecosys.com [192.168.55.1]) by mail.appl-ecosys.com (Postfix) with ESMTP id 9F27D99356 for ; Wed, 13 Feb 2019 06:28:18 -0800 (PST) Date: Wed, 13 Feb 2019 06:28:18 -0800 (PST) From: Rich Shepard To: "pgsql-generallists.postgresql.org" Subject: Re: Subquery to select max(date) value In-Reply-To: Message-ID: References: <2780074d-3b87-b154-8bc6-a0f898fbdde2@openvistas.net> 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 Tue, 12 Feb 2019, Ken Tanzer wrote: > If that's getting you what you want, then great and more power to you. It > looks like you'll only get people who have a next_contact in your target > window there. You might also consider something like this... > > select > p.person_id, > p.lname, > p.fname, > p.direct_phone, > o.org_name, > a.next_contact > from > people as p > LEFT JOIN organizations o USING (person_id) > LEFT JOIN ( > SELECT > DISTINCT ON (person_id) > person_id, > next_contact > FROM activities a > -- WHERE ??? > ORDER BY person_id,next_contact DESC > ) a USING (person_id) > ; I modified this to restrict the time and ignore nulls by replacing the question marks: WHERE a.next_contact <= 'today' and a.next_contact > '2018-12-31' and a.next_contact is not null For a reason I've not yet found, the last condition is not observed; i.e., those rows with null next_contact dates appear in the results. Position in the sequence makes no difference. What might cause this? Regards, Rich