X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id 0757DD1C9C4 for ; Fri, 9 Apr 2004 00:33:00 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (neptune.hub.org [200.46.204.2]) (amavisd-new, port 10024) with ESMTP id 19120-09 for ; Fri, 9 Apr 2004 00:32:57 -0300 (ADT) Received: from tht.net (vista.tht.net [216.126.88.2]) by svr1.postgresql.org (Postfix) with ESMTP id 154B6D1C995 for ; Fri, 9 Apr 2004 00:32:58 -0300 (ADT) Received: from [134.22.71.250] (dyn-71-250.tor.dsl.tht.net [134.22.71.250]) by tht.net (Postfix) with ESMTP id 78AEF76A93; Thu, 8 Apr 2004 23:32:29 -0400 (EDT) Subject: Re: SQL challenge--top 10 for each key value? From: Rod Taylor To: Greg Stark Cc: Jeff Boes , pgsql-sql@postgresql.org In-Reply-To: <87r7uyf3ki.fsf@stark.xeocode.com> References: <33af4fa4e4ec230574cefcff737ea40a@news.teranews.com> <87r7uyf3ki.fsf@stark.xeocode.com> Content-Type: text/plain Message-Id: <1081481466.56361.808.camel@jester> Mime-Version: 1.0 X-Mailer: Ximian Evolution 1.4.5 Date: Thu, 08 Apr 2004 23:31:07 -0400 Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200404/69 X-Sequence-Number: 17444 On Thu, 2004-04-08 at 19:33, Greg Stark wrote: > Jeff Boes writes: > > > I headed off in the direction of groups of SELECTs and UNIONs, and quit when I > > got to something like four levels of "SELECT ... AS FOO" ... > > four? wimp, that's nothing! > > ok, seriously I think there's no way to do this directly with straight SQL. > You would have to define a non-immutable function that has some temporary > storage where it keeps track of how many it has seen. I don't believe that is true, though it is certainly is in PostgreSQL. The spec has the ability to apply a progressive aggregate on the results of a query (window function). Meaning you can accomplish things like counting (ROW_NUMBER) or running totals. Something along the lines of the below would accomplish what you want according to spec. ROW_NUMBER() is a spec defined function. (6.10 of SQL200N) SELECT * FROM (SELECT ROW_NUMBER() OVER (DISTINCT query) AS counter ) WHERE counter > 10;