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 33D8DD1D085 for ; Thu, 8 Apr 2004 17:11:18 -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 96448-05 for ; Thu, 8 Apr 2004 17:11:02 -0300 (ADT) Received: from news.hub.org (news.hub.org [200.46.204.72]) by svr1.postgresql.org (Postfix) with ESMTP id F1EF4D1E9C1 for ; Thu, 8 Apr 2004 17:10:29 -0300 (ADT) Received: from news.hub.org (news.hub.org [200.46.204.72]) by news.hub.org (8.12.9/8.12.9) with ESMTP id i38KATSx011696 for ; Thu, 8 Apr 2004 20:10:29 GMT (envelope-from news@news.hub.org) Received: (from news@localhost) by news.hub.org (8.12.9/8.12.9/Submit) id i38K3IE1010235 for pgsql-sql@postgresql.org; Thu, 8 Apr 2004 20:03:18 GMT X-Abuse-Report: abuse@teranews.com Message-ID: <33af4fa4e4ec230574cefcff737ea40a@news.teranews.com> Date: Thu, 08 Apr 2004 19:55:33 GMT Lines: 40 From: Jeff Boes User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4.2) Gecko/20040329 X-Accept-Language: en-us, en MIME-Version: 1.0 X-Newsgroups: comp.databases.postgresql.sql Subject: SQL challenge--top 10 for each key value? Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit To: pgsql-sql@postgresql.org X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200404/67 X-Sequence-Number: 17442 Offered up for anyone with time on their hands. I fiddled around with this for half an afternoon, then gave up and did it programmatically in Perl. Given a table that looks something like this: id | INTEGER query | INTEGER checksum | char(32) score | INTEGER include | BOOLEAN The table is unique by "id". "Checksum" may be repeated, but I only care if it is repeated within a given group by "query". ("query" is non-null.) I can get the top scorer for each "query" row by something like this: SELECT * FROM ( SELECT DISTINCT ON (checksum) * FROM my_table ORDER BY checksum, score DESC) ORDER BY query; How would you go about getting the top N (say, the top 10) for each query? And then, if that's too easy for you--consider a further case where I want every row for a given "query" that has "include" TRUE, and enough non-"include" rows to make N. I might end up with more than N rows for a given value of "query" if there were more than N with "include" set. 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" ... -- Jeff Boes vox 269.226.9550 ext 24 Database Engineer fax 269.349.9076 Nexcerpt, Inc. http://www.nexcerpt.com ...Nexcerpt... Extend your Expertise