Re: How do I write this query? Distinct, Group By, Order By?

Поиск
Список
Период
Сортировка
От Josh Kupershmidt
Тема Re: How do I write this query? Distinct, Group By, Order By?
Дата
Msg-id AANLkTimaKkHXq0TXiFmsEtHMM53aQ759etVsQ-zXK5CQ@mail.gmail.com
обсуждение исходный текст
Ответ на How do I write this query? Distinct, Group By, Order By?  (Min Yin <yin@AI.SRI.COM>)
Список 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 по дате отправления:

Предыдущее
От: Magnus Hagander
Дата:
Сообщение: Re: querying the version of libpq
Следующее
От: Georgi Ivanov
Дата:
Сообщение: Why i see several postgres server processes sometimes ?