Received: from magus.postgresql.org (magus.postgresql.org [87.238.57.229]) by mail.postgresql.org (Postfix) with ESMTP id C35B21B52349 for ; Wed, 23 May 2012 07:21:42 -0300 (ADT) Received: from plane.gmane.org ([80.91.229.3]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1SX8hI-00080y-6n for pgsql-sql@postgresql.org; Wed, 23 May 2012 10:21:41 +0000 Received: from list by plane.gmane.org with local (Exim 4.69) (envelope-from ) id 1SX8h3-0003sY-Sv for pgsql-sql@postgresql.org; Wed, 23 May 2012 12:21:25 +0200 Received: from 217.110.94.67 ([217.110.94.67]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Wed, 23 May 2012 12:21:25 +0200 Received: from spam_eater by 217.110.94.67 with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Wed, 23 May 2012 12:21:25 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Thomas Kellerer Subject: Re: left outer join only select newest record Date: Wed, 23 May 2012 12:22:56 +0200 Lines: 39 Message-ID: References: <201205231027.39198.gary.stainburn@ringways.co.uk> <53C6FD0FE48B43C0AD419648FDC8D943@marktestcr.marktest.pt> <201205231047.27372.gary.stainburn@ringways.co.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: usenet@dough.gmane.org X-Gmane-NNTP-Posting-Host: 217.110.94.67 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.23) Gecko/20090812 Thunderbird/2.0.0.23 Mnenhy/0.7.6.666 In-Reply-To: <201205231047.27372.gary.stainburn@ringways.co.uk> X-Pg-Spam-Score: -0.7 (/) X-Archive-Number: 201205/67 X-Sequence-Number: 36615 Gary Stainburn, 23.05.2012 11:47: > Here is a select to show the problem. There is one stock record and two tax > records. What I'm looking for is how I can return only the second tax record, > the one with the highest ud_id > > select s_stock_no, s_regno, s_vin, s_created, ud_id, ud_handover_date from > stock s left outer join used_diary u on s.s_regno = u.ud_pex_registration > where s_stock_no = 'UL15470'; > > s_stock_no | s_regno | s_vin | s_created | > ud_id | ud_handover_date > ------------+---------+-------------------+----------------------------+-------+------------------ > UL15470 | YG12*** | KNADN312LC6****** | 2012-05-21 09:15:31.569471 | > 41892 | 2012-04-06 > UL15470 | YG12*** | KNADN312LC6****** | 2012-05-21 09:15:31.569471 | > 42363 | 2012-05-16 > (2 rows) > Something like: select * from ( select s_stock_no, s_regno s_vin, s_created, ud_id, ud_handover_date, row_number() over (partition by s_stock_no order by ud_id desc) as rn from stock s left outer join used_diary u on s.s_regno = u.ud_pex_registration where s_stock_no = 'UL15470' ) t where rn = 1 The "partition by s_stock_no order" isn't really necessary as your where clause already limits that to a single stock_no. But in case you change that statement to return more than one stock_no in the future it will be necessary.