Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id 97B93632774 for ; Sat, 6 Mar 2010 09:31:41 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 73902-04 for ; Sat, 6 Mar 2010 13:31:30 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sargon.lncsa.com (mail.lncsa.com [213.215.28.11]) by mail.postgresql.org (Postfix) with ESMTP id 11698632A32 for ; Sat, 6 Mar 2010 09:31:31 -0400 (AST) Received: from localhost (localhost.localdomain [127.0.0.1]) by sargon.lncsa.com (Postfix) with ESMTP id B21DC301E6E7 for ; Sat, 6 Mar 2010 14:31:28 +0100 (CET) X-Virus-Scanned: Debian amavisd-new at lncsa.com Received: from sargon.lncsa.com ([127.0.0.1]) by localhost (sargon.lncsa.com [127.0.0.1]) (amavisd-new, port 10024) with ESMTP id NVUTgEfiSy7z for ; Sat, 6 Mar 2010 14:31:28 +0100 (CET) Received: from zenon.apartia.fr (zenon.apartia.fr [10.0.3.1]) (using TLSv1 with cipher DHE-RSA-AES256-SHA (256/256 bits)) (Client CN "zenon.apartia.fr", Issuer "ca.apartia.fr" (verified OK)) by sargon.lncsa.com (Postfix) with ESMTP id 8C40F301E6E2 for ; Sat, 6 Mar 2010 14:31:28 +0100 (CET) Received: from delos.apartia.fr (delos.apartia.fr [10.0.3.107]) by zenon.apartia.fr (Postfix) with ESMTP id D78345898D202 for ; Sat, 6 Mar 2010 14:31:27 +0100 (CET) Received: by delos.apartia.fr (Postfix, from userid 1000) id 9631A201D3487; Sat, 6 Mar 2010 14:31:27 +0100 (CET) Date: Sat, 6 Mar 2010 14:31:27 +0100 From: Louis-David Mitterrand To: pgsql-sql@postgresql.org Subject: Re: an aggregate to return max() - 1 value? Message-ID: <20100306133127.GA6562@apartia.fr> Mail-Followup-To: pgsql-sql@postgresql.org References: <20100304200913.GA24865@apartia.fr> <4B901488.6080502@fmed.uba.ar> <407d949e1003041253g1812b85bhe8ce0fbd7b1f7159@mail.gmail.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <407d949e1003041253g1812b85bhe8ce0fbd7b1f7159@mail.gmail.com> User-Agent: Mutt/1.5.20 (2009-06-14) X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.599 tagged_above=-10 required=5 tests=BAYES_00=-2.599 X-Spam-Level: X-Archive-Number: 201003/42 X-Sequence-Number: 33749 On Thu, Mar 04, 2010 at 08:53:10PM +0000, Greg Stark wrote: > SELECT col FROM tab ORDER BY col DESC OFFSET 1 LIMIT 1 > > In 8.4 OLAP window functions provide more standard and flexibility > method but in this case it wouldn't perform as well: > > postgres=# select i from (select i, rank() over (order by i desc) as r > from i) as x where r = 2; > i > ---- > 99 > (1 row) > > postgres=# select i from (select i, dense_rank() over (order by i > desc) as r from i) as x where r = 2; > i > ---- > 99 > (1 row) Wow, I didn't know about window functions until now. It's exactly what I need. Thanks Greg, and also thanks to others who sent their suggestion. Cheers,