X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id 5743FD1B537 for ; Mon, 17 Nov 2003 16:39:15 +0000 (GMT) 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 04418-09 for ; Mon, 17 Nov 2003 12:38:43 -0400 (AST) Received: from martin.sysdetect.com (martin.sysdetect.com [65.209.102.1]) by svr1.postgresql.org (Postfix) with ESMTP id A9500D1B54C for ; Mon, 17 Nov 2003 12:38:42 -0400 (AST) Received: (from mail@localhost) by martin.sysdetect.com (8.11.4/8.11.3) id hAHGcg402482 for ; Mon, 17 Nov 2003 16:38:42 GMT Received: from winwood.sysdetect.com(172.16.1.1) via SMTP by mail.sysdetect.com, id smtpdA26397; Mon Nov 17 16:38:38 2003 Received: from sysd.com (thriller.sysdetect.com [172.16.1.33]) by winwood.sysdetect.com (8.11.6/8.11.6) with ESMTP id hAHGccb19973 for ; Mon, 17 Nov 2003 11:38:38 -0500 Message-ID: <3FB8F98D.1010707@sysd.com> Date: Mon, 17 Nov 2003 11:38:37 -0500 From: Rich Cullingford User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030703 X-Accept-Language: en-us, en MIME-Version: 1.0 To: pgsql-performance@postgresql.org Subject: Top n queries and GROUP BY Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200311/136 X-Sequence-Number: 4696 All, This is a straight SQL question, maybe not appropriate for a performance list, but... I have a simple stock holdings setup: => select * from t1; nam | co | num -----+-----------+------ joe | ibm | 600 abe | ibm | 1500 joe | cisco | 1200 abe | cisco | 800 joe | novell | 500 joe | microsoft | 200 What I would like to see is a Top-n-holdings-by-name", e.g, for n=2: nam | co | num ----------+--------+----- joe | cisco | 1200 joe | ibm | 600 abe | ibm | 1500 abe | cisco | 800 I can get part of the way by using a LIMIT clause in a subquery, e.g, => select 'abe', a.co, a.num from (select co, num from t1 where nam='abe' order by num desc limit 2) as a; ?column? | co | num ----------+-------+------ abe | ibm | 1500 abe | cisco | 800 but I can't figure out a correlated subquery (or GROUP BY arrangement or anything else) that will cycle through the names. I vaguely remember that these kinds or queries are hard to do in standard SQL, but I was hoping that PG, with its extensions... Thanks, Rich Cullingford rculling@sysd.com