Re: fetch first rows of grouped data

From: Michael Glaesemann <grzm(at)seespotcode(dot)net>
To: Joel Richard <postgres(at)joelrichard(dot)com>
Cc: "D'Arcy J(dot)M(dot) Cain" <darcy(at)druid(dot)net>, Claudia Kosny <ckosny(at)gmx(dot)net>, sql pgsql <pgsql-sql(at)postgresql(dot)org>
Subject: Re: fetch first rows of grouped data
Date: 2007-08-27 18:12:48
Message-ID: 60F656A0-805D-4C3B-BCA5-742AC6C866E0@seespotcode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

[Please don't top post as it makes the discussion more difficult to
follow.]

On Aug 27, 2007, at 12:34 , Joel Richard wrote:

>
> On Aug 27, 2007, at 12:51 PM, D'Arcy J.M. Cain wrote:
>
>> On Mon, 27 Aug 2007 18:36:47 +0200
>> Claudia Kosny <ckosny(at)gmx(dot)net> wrote:
>>> I have a list of events that take place in a certain city at a
>>> certain
>>> date. Now I would like to have the first two (ordered by date)
>>> events
>>> for each city.
>>>
>>> Is there a way to do this with one query?
>>> I am using PostgreSQL 7.4.
>>
>> I believe you are looking for the LIMIT keyword. Check the docs
>> on the
>> web site.

> That's what I thought at first, but this is not the case. She's
> looking for the first two dates in -each- city in the table. I
> initially thought that this could be accomplished with GROUP BY and
> LIMIT, but GROUP BY can only give you the first date for each city,
> not the first two dates for each city.
>
> So far, I haven't come up with any clever ideas. I'm not sure this
> can be done in SQL.
>
> --Joel
>

I can't think of an easy way to do it, but certainly can do it in SQL
using correlated subqueries, something like

select city, event, event_date, (
select count(event)
from events i
where i.city = o.city
and i.event_date < o.event_date
and event_date > current_date -- make sure they're future
events
) as nearness_rank
from events o
where event_date > current_date -- make sure they're future events
having nearness_rank <= 1;

Note that this can potentially show more than 2 events if the most
recent upcoming events "tie" (have the same event_date).

Michael Glaesemann
grzm seespotcode net

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message D'Arcy J.M. Cain 2007-08-27 18:15:52 Re: fetch first rows of grouped data
Previous Message Joel Richard 2007-08-27 17:34:09 Re: fetch first rows of grouped data