Re: SQL challenge--top 10 for each key value?

From: Rod Taylor <pg(at)rbt(dot)ca>
To: Greg Stark <gsstark(at)mit(dot)edu>
Cc: Jeff Boes <jboes(at)nexcerpt(dot)com>, pgsql-sql(at)postgresql(dot)org
Subject: Re: SQL challenge--top 10 for each key value?
Date: 2004-04-09 03:31:07
Message-ID: 1081481466.56361.808.camel@jester
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Thu, 2004-04-08 at 19:33, Greg Stark wrote:
> Jeff Boes <jboes(at)nexcerpt(dot)com> 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
<rest of query>
)
WHERE counter > 10;

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2004-04-09 06:11:44 Re: SQL challenge--top 10 for each key value?
Previous Message Greg Stark 2004-04-08 23:33:01 Re: SQL challenge--top 10 for each key value?