From: Stephan Szabo <sszabo@megazone.bigpanda.com>
To: Ram Nathaniel <ram_nathaniel@hotmail.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: SQL syntax extentions - to put postgres ahead in the race
Date: Thu, 5 Aug 2004 22:22:33 -0700 (PDT)
Message-ID: <20040805220147.O92438@megazone.bigpanda.com> (raw)
In-Reply-To: <BAY7-DAV12V0KUvkRkZ000f7e18@hotmail.com>
References: <BAY7-DAV12V0KUvkRkZ000f7e18@hotmail.com>
On Thu, 5 Aug 2004, Ram Nathaniel wrote:
>
> 1) The operator "of max":
> suppose I have a table "grades" of 3 fields: class/student/grade where I
> store many grades of many students of many classes. I want to get the
> name of the highest scoring student in each class. Note that there may
> be many students with the same grade, but for starters let's say there
> is a primary key of class+grade.
>
> My query would now be:
> select student from grades where class+'#'+grade in
> (
> select class+'#'+max(grade) from grades group by class
> ) a
As a side note, I'd think that something like:
select student from grades where (class,grade) in
(select class, max(grade) from grades group by class);
should avoid textual operations. I'm assuming the + above are meant to be
concatenation (||).
> The optimal would be to introduce a new operator "of max" that would be used as follows:
>
> select student of max(grade) from grades group by class
PostgreSQL provides an extension called DISTINCT ON.
Something like
select distinct on (class) student from grades order by class, grade
desc;
should get you one arbitrary student with the highest grade in his or her
class.
If you want to order by the grades, I think you need a layer around it.
If you don't care about the class order, you might consider making the
class ordering desc as well to make it easier to use a multi-column index
on (class,grade).
> 2) aggregated concatenation:
Theoretically, you should be able to do this right now in PostgreSQL with
user defined aggregates (although you can't pass a second argument
currently for the separator). I believe that an ordered subquery in FROM
will currently allow you to get an ordered aggregate, or perhaps you'd
have to turn off hash aggregation, but I think you should be able to get
it to keep the ordering.
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-sql@postgresql.org
Cc: sszabo@megazone.bigpanda.com, ram_nathaniel@hotmail.com
Subject: Re: SQL syntax extentions - to put postgres ahead in the race
In-Reply-To: <20040805220147.O92438@megazone.bigpanda.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