This is my query:
select locid,tlid,locdescription from (
select locid, tlid, locdescription
from
trip_log left join trip_log_det on tlid=tldtripid
left join locations on tldlocation=locid
where tlid=50 order by tldid
) as foo group by locid,tlid,locdescription
The point of using a subquery is to get data back ordered as per the internal query, so sorted by tldid
. I do not need tldid
in the data as it is a serial column and it would nullify the group by
statement.
Is there a way to tell the subquery to maintain the ordering of the internal query?
Best Answer
You don't need a subquery at all. But you have to decide what ordering you want.
After the
group by
there is notldid
values any more. And every group will be made by collapsing many rows (with differenttldid
values) into one row. Which of them should be used for the ordering? Is it the maximum, the mimimum or some other?You can write for example:
In Postgres, you could also use the non-standard
DISTINCT ON
syntax to achieve the same result. This is more flexible, as you can have thetldid
and other (non-grouped) columns in theselect
list as well: