Re: Distinct on a non-sort column

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Re: Distinct on a non-sort column
Дата
Msg-id 14541.1320522570@sss.pgh.pa.us
обсуждение исходный текст
Ответ на Distinct on a non-sort column  (Cstdenis <lists@on-track.ca>)
Ответы Re: Distinct on a non-sort column  (Cstdenis <lists@on-track.ca>)
Список pgsql-general
Cstdenis <lists@on-track.ca> writes:
> I am trying to write a query that selects recent submissions (sorted by
> submission_date) but only selects the most recent one for each user_id.

> example query: /select distinct on (user_id) * from stories order by
> date_submitted desc limit 10;/

> However postgres will not allow me to filter out duplicate rows with
> distinct unless I sort on that column, which would product useless
> results for me.

Do the DISTINCT ON in a sub-query, with an ORDER BY appropriate for that
task, and then re-sort the rows the way you want them presented in the
outer query.

    SELECT ... FROM
        (SELECT DISTINCT ON ... ORDER BY ...) ss
    ORDER BY ...;

            regards, tom lane

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

Предыдущее
От: Tair Sabirgaliev
Дата:
Сообщение: Re: Distinct on a non-sort column
Следующее
От: Oliver Kohll - Mailing Lists
Дата:
Сообщение: explain analyse and nested loop joins