Wednesday, November 21. 2007Using Distinct ON to return newest order for each customerPrinter FriendlyComments
Display comments as
(Linear | Threaded)
Thanks for this great tip, it boosted some of my slowest queries by factor 100! :)
That is very nice and it does work. It seems DISTINCT requires the first item in ORDER BY to match - and that's customer_id, not order_date. Is there a way to then order that result by order date?
Leif,
Yes wrap the whole thing in a sub select SELECT * FROM ( SELECT DISTINCT ON (c.customer_id) c.customer_id, c.customer_name, o.order_date, o.order_amount, o.order_id FROM customers c LEFT JOIN orders O ON c.customer_id = o.customer_id ORDER BY c.customer_id, o.order_date DESC, o.order_id DESC) As foo ORDER BY foo.order_date; |
Entry's LinksQuicksearchCalendar
Categories
Blog Administration |
Comparison of Microsoft SQL Server 2005, MySQL 5, and PostgreSQL 8.3 The below is by no means an exhaustive comparison of these 3 databases and functionality may not be necessarily ordered in order of importance. These are just our experiences with us
Tracked: May 13, 19:02
Tracked: Jul 12, 22:27