Re: select distinct w/order by

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Re: select distinct w/order by
Дата
Msg-id 9918.1080762103@sss.pgh.pa.us
обсуждение исходный текст
Ответ на select distinct w/order by  ("John Liu" <johnl@emrx.com>)
Ответы Re: select distinct w/order by  ("scott.marlowe" <scott.marlowe@ihs.com>)
Список pgsql-general
"John Liu" <johnl@emrx.com> writes:
> The original simple SQL -
> select distinct atcode from TMP order by torder;

This is not "simple", it is "broken SQL with an undefined result".

If DISTINCT merges multiple rows with the same atcode, how are we
supposed to know which row's value of torder to sort the merged
row on?

Your other database was no doubt making a random choice and giving
you a random result ordering in consequence.  You need to think harder
about what behavior you really want.

Once you can define the behavior (ie, just which torder you want to use)
you can probably implement it with something like

select atcode from
(select distinct on (atcode) atcode, torder from table
 order by atcode, ???
) ss
order by torder;

where the ??? ordering determines which torder you get in each atcode group.
See the SELECT DISTINCT ON example in the SELECT reference page.

            regards, tom lane

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

Предыдущее
От: William White
Дата:
Сообщение: Re: Question about rtrees (overleft replacing left in nodes)
Следующее
От: "Dann Corbit"
Дата:
Сообщение: Re: Wich hardware suits best for large full-text indexed databases