Re: pgsql aggregate: conditional max

Поиск
Список
Период
Сортировка
От Michael Fuhr
Тема Re: pgsql aggregate: conditional max
Дата
Msg-id 20060312054212.GA25423@winnie.fuhr.org
обсуждение исходный текст
Ответ на pgsql aggregate: conditional max  (Weimao Ke <wke@indiana.edu>)
Ответы Re: pgsql aggregate: conditional max  (Weimao Ke <wke@indiana.edu>)
Список pgsql-sql
On Sun, Mar 12, 2006 at 12:09:48AM -0500, Weimao Ke wrote:
> I want to group by "aid" and choose the category (i.e., "cat") with the 
> largest "weight":
> 
> aid   |   max_weighted_cat
> ----+---------------------
> a1   |   Other
> a2   |   Drama
> a3   |   Adult

PostgreSQL has a non-standard DISTINCT ON clause that would work.
See the weather_reports example in the documentation for SELECT:

http://www.postgresql.org/docs/8.1/interactive/sql-select.html

Try this query against your example data:

SELECT DISTINCT ON (aid) aid, cat
FROM tablename
ORDER BY aid, weight DESC, cat;

If multiple rows for a given aid match that aid's max weight then
the above query will return the first matching row according to the
given sort order.

Some people object to DISTINCT ON because it's non-deterministic if
you don't order by enough columns.  Here's something more standard;
it'll return all rows that match a given aid's max weight:

SELECT aid, cat
FROM tablename AS t
JOIN (SELECT aid, max(weight) AS weight     FROM tablename     GROUP BY aid) AS s USING (aid, weight);

-- 
Michael Fuhr


В списке pgsql-sql по дате отправления:

Предыдущее
От: Jeffrey Melloy
Дата:
Сообщение: Re: pgsql aggregate: conditional max
Следующее
От: Michael Fuhr
Дата:
Сообщение: Re: pgsql aggregate: conditional max