Re: How do I write this query? Distinct, Group By, Order By? - Mailing list pgsql-general

From Josh Kupershmidt
Subject Re: How do I write this query? Distinct, Group By, Order By?
Date
Msg-id AANLkTimaKkHXq0TXiFmsEtHMM53aQ759etVsQ-zXK5CQ@mail.gmail.com
Whole thread Raw
In response to How do I write this query? Distinct, Group By, Order By?  (Min Yin <yin@AI.SRI.COM>)
List pgsql-general
On Wed, Oct 6, 2010 at 3:34 AM, Min Yin <yin@ai.sri.com> wrote:
>  Hi Yes that works too. Many Thanks!
>
> Now as you have probably , what I really want to get the full record of the
> user, which is in another table called users. The following query doesn't
> seem to work
>
> select users.id, users.* from users join orders on users.id=orders.user_id
> group by users.id order by max(orders.order_time) desc;
>
> If all I can get is a list of user_id, then can I get the list of user
> records in ONE 2nd query?

I bet there's other ways to do this, but this should work (you need
8.4 or later to use the WITH(...) clause):

WITH recent_users AS (
   SELECT orders.user_id AS user_id, MAX(orders.order_time) AS max_order_time
   FROM orders
   GROUP BY orders.user_id
)
  SELECT recent_users.max_order_time, users.*
    FROM recent_users
    INNER JOIN users
    ON users.id = recent_users.user_id
  ORDER BY recent_users.max_order_time;

Josh

pgsql-general by date:

Previous
From: Magnus Hagander
Date:
Subject: Re: querying the version of libpq
Next
From: Georgi Ivanov
Date:
Subject: Why i see several postgres server processes sometimes ?