pg.ddx.io  pgsql-performance@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Rich Cullingford <rculling@sysd.com>
To: pgsql-performance@postgresql.org
Subject: Top n queries and GROUP BY
Date: Mon, 17 Nov 2003 11:38:37 -0500
Message-ID: <3FB8F98D.1010707@sysd.com> (raw)

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





view thread (3+ messages)  latest in thread

Message-ID: <3FB8F98D.1010707@sysd.com>
Permalink:  ../3FB8F98D.1010707@sysd.com/
Also on:    postgresql.org/message-id/3FB8F98D.1010707@sysd.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-performance@postgresql.org
  Cc: rculling@sysd.com
  Subject: Re: Top n queries and GROUP BY
  In-Reply-To: <3FB8F98D.1010707@sysd.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox