From: | Michael Fuhr <mike(at)fuhr(dot)org> |
---|---|
To: | stephen(at)thunkit(dot)com |
Cc: | pgsql-general(at)postgresql(dot)org |
Subject: | Re: 'distinct on' and 'order by' conflicts of interest |
Date: | 2004-12-31 17:36:36 |
Message-ID: | 20041231173636.GA23293@winnie.fuhr.org |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On Fri, Dec 31, 2004 at 10:48:21AM -0600, stephen(at)thunkit(dot)com wrote:
> It has come up several times on the various postgresql lists that in order
> to get around the requirement of DISTINCT ON parameters matching the first
> ORDER BY parameters, wrap the distinct query in a new 'order by' query:
>
> select * from (select distinct on (a) a,b,c from foo order by a) order by c
>
> however, this will not work when ordering by 'a' will put the wrong record
> first, making it choose the wrong record via distinct on. The 'order by
> c' superquery no longer has the correct recordset to sort.
You should be ordering by more than just "a" in the DISTINCT ON
query. SELECT DISTINCT ON (a) gives you the first row for each "a"
value; if you don't specify an order for additional fields then
you'll get some arbitrary row. See the weather_reports example in
the documentation for SELECT in the "SQL Commands" part of the
documentation.
> I cannot figure out how to have postgresql first sort the results (on
> something other than the 'distinct on' parameters) and then do a recordset
> culling by only part of the record. Does anyone have the syntax for this?
Define the problem, not how you think it should be solved. What
are you trying to do? If you can't get the query to work, then
please post SQL statements to create and populate a table and
describe the query results you'd like to see.
--
Michael Fuhr
http://www.fuhr.org/~mfuhr/
From | Date | Subject | |
---|---|---|---|
Next Message | Joshua D. Drake | 2004-12-31 17:40:27 | Re: Large Objects |
Previous Message | stephen | 2004-12-31 16:48:21 | 'distinct on' and 'order by' conflicts of interest |