Re: select distinct w/order by - Mailing list pgsql-general

From John Liu
Subject Re: select distinct w/order by
Date
Msg-id 200404011508.i31F8tcU023432@mail.stihealthcare.com
Whole thread Raw
In response to Re: select distinct w/order by  ("scott.marlowe" <scott.marlowe@ihs.com>)
List pgsql-general
Sorry, the query you provided works in Pg, my mistake :!
select atcode from table group by atcode order by max(torder);

johnl
-----Original Message-----
From: scott.marlowe [mailto:scott.marlowe@ihs.com]
Sent: Wednesday, March 31, 2004 4:35 PM
To: Tom Lane
Cc: John Liu; pgsql-general@postgresql.org
Subject: Re: [GENERAL] select distinct w/order by

On Wed, 31 Mar 2004, Tom Lane wrote:

> "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.

I did it like this:

select atcode from table group by atcode order by max(toorder);

Is that equivalent?


pgsql-general by date:

Previous
From: "Rajat Katyal"
Date:
Subject: PERFORM statement inside procedure
Next
From: Bricklen
Date:
Subject: Re: row-level security model