Re: value from max row in group by

From: Marc Mamin <M(dot)Mamin(at)intershop(dot)de>
To: Venky Kandaswamy <venky(at)adchemy(dot)com>, Gary Stainburn <gary(dot)stainburn(at)ringways(dot)co(dot)uk>, "pgsql-sql(at)postgresql(dot)org" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: value from max row in group by
Date: 2013-07-25 18:53:06
Message-ID: B6F6FD62F2624C4C9916AC0175D56D880CE11137@jenmbs01.ad.intershop.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


>________________________________________
>Von: pgsql-sql-owner(at)postgresql(dot)org [pgsql-sql-owner(at)postgresql(dot)org]&quot; im Auftrag von &quot;Venky >Kandaswamy [venky(at)adchemy(dot)com]
>
>You can use Postgres WINDOW functions for this in several different ways. For example, one way of doing it:
>
>select stts_id, last_value(stts_offset) over (partition by stts_id order by stts_offset desc)
> + last_value(stts_duration) over (partition by stts_id order by stts_offset desc)
>from table
>group by stts_id;

another simple solution with distinct on:

select distinct on (stts_id, stts_offset) stts_id, stts_offset+stts_duration
from table
order by stts_id, stts_offset desc

Marc Mamin

________________________________________
From: pgsql-sql-owner(at)postgresql(dot)org <pgsql-sql-owner(at)postgresql(dot)org> on behalf of Gary Stainburn <gary(dot)stainburn(at)ringways(dot)co(dot)uk>
Sent: Thursday, July 25, 2013 10:57 AM
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: [SQL] value from max row in group by

As usual, once I've asked the question, I find the answer myself.

However, it *feels* like there should be a more efficient way. Can anyone
comment or suggest a better method?

timetable=> select stts_id, stts_offset+stts_duration as total_duration
timetable-> from standard_trip_sections
timetable-> where (stts_id, stts_offset) in
timetable-> (select stts_id, max(stts_offset) from standard_trip_sections
group by stts_id);
stts_id | total_duration
---------+----------------
1 | 01:35:00
2 | 01:35:00
3 | 01:08:00
4 | 01:38:00
5 | 01:03:00
6 | 01:06:00
(6 rows)

timetable=>

--
Sent via pgsql-sql mailing list (pgsql-sql(at)postgresql(dot)org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql

--
Sent via pgsql-sql mailing list (pgsql-sql(at)postgresql(dot)org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Gary Stainburn 2013-07-26 08:18:51 Re: value from max row in group by
Previous Message Venky Kandaswamy 2013-07-25 18:03:58 Re: value from max row in group by