Received: from localhost (unknown [200.46.204.184]) by postgresql.org (Postfix) with ESMTP id 7874E9F9BF5 for ; Wed, 19 Sep 2007 05:13:53 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.184]) (amavisd-maia, port 10024) with ESMTP id 23006-06 for ; Wed, 19 Sep 2007 05:13:43 -0300 (ADT) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.5 Received: from ciao.gmane.org (main.gmane.org [80.91.229.2]) by postgresql.org (Postfix) with ESMTP id 6EBB39F9BEA for ; Wed, 19 Sep 2007 05:13:47 -0300 (ADT) Received: from list by ciao.gmane.org with local (Exim 4.43) id 1IXugq-0003RU-FF for pgsql-sql@postgresql.org; Wed, 19 Sep 2007 10:13:44 +0200 Received: from cpe.atm2-0-1261189.0x503fa7b2.bynxx8.customer.tele.dk ([80.63.167.178]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Wed, 19 Sep 2007 10:13:44 +0200 Received: from nis by cpe.atm2-0-1261189.0x503fa7b2.bynxx8.customer.tele.dk with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Wed, 19 Sep 2007 10:13:44 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: =?UTF-8?B?TmlzIErDuHJnZW5zZW4=?= Subject: Re: Table transform query Date: Wed, 19 Sep 2007 10:13:08 +0200 Lines: 39 Message-ID: References: <6C0CF58A187DA5479245E0830AF84F4218CF1F@poweredge.attiksystem.ch> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Complaints-To: usenet@sea.gmane.org X-Gmane-NNTP-Posting-Host: cpe.atm2-0-1261189.0x503fa7b2.bynxx8.customer.tele.dk User-Agent: Thunderbird 2.0.0.6 (Windows/20070728) In-Reply-To: X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200709/134 X-Sequence-Number: 29347 Rodrigo De León skrev: > On 9/18/07, Philippe Lang wrote: >> ... into this: >> >> >> serial dateL dateR >> -------------------- >> 1 1 2 >> 1 4 >> 2 1 2 >> 3 1 3 >> 4 2 3 >> 5 3 > > SELECT t1.serial, t1.DATE AS datel, t2.DATE AS dater > FROM t t1 LEFT JOIN t t2 ON( t1.serial = t2.serial > AND t1.DATE < t2.DATE) > WHERE t1.delivery = 'L' > AND ( t2.delivery = 'R' > OR t2.delivery IS NULL) > ORDER BY t1.serial This only works if (serial, delivery) is unique - which it doesn't appear to be, from the solution posted by Philippe himself (which does a LIMIT 1 in the subquery). A take on a self-join: SELECT t1.serial, t1.date as dateL, MIN(t2.date) as dateR FROM t t1 LEFT JOIN t t2 ON t1.serial = t2.serial AND t1.date < t2.date AND t2.delivery = 'R' WHERE t1.delivery = 'L' GROUP BY t1.serial, t1.date Whether this is any clearer, or runs faster, than the correlated subquery (which could be simplified by using MIN instead of LIMIT 1) is up for debate and test, respectively. Nis