Re: SQL subqueries newbie help

From: Rod Taylor <rbt(at)rbt(dot)ca>
To: Alexei Chetroi <lexoid(at)lexa(dot)uniflux-line(dot)net>
Cc: Pgsql-Sql <pgsql-sql(at)postgresql(dot)org>
Subject: Re: SQL subqueries newbie help
Date: 2003-09-07 13:09:35
Message-ID: 1062940175.54737.22.camel@jester
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Sun, 2003-09-07 at 07:42, Alexei Chetroi wrote:
> On Sat, Sep 06, 2003 at 01:21:36PM -0400, Rod Taylor wrote:
> > > I'd like to write a query which returns following information regarding
> > > each item: item, date of very first event, very last event.
> > > Is this possible? I think I can write several SELECT queries and
> > > procces them by an application or possibly write some procedure, but
> > > what is better solution?
> >
> > Something like the below should do it:
> >
> > SELECT item
> > , min_date
> > , min_event
> > , max_date
> > , max_event
> > FROM items
> > JOIN (SELECT min(date) AS min_date
> > , event AS min_event
> > , item
> > FROM events
> > GROUP BY item) AS mn USING (item)
> [skip]
>
> Thanks everybody for responses. I'm trying this one, but psql complains
> on queries like "SELECT min(date), event FROM events GROUP BY item" that
> events must be GROUPed or used in an aggregate function. Why this
> happens and why it needs be so?

Oh yeah, sorry. It needs to be like that because otherwise it is unsure
what value to use for event. What you really want is a min function
that runs a min on date, and returns the appropriate event -- which
doesn't exist, but I believe could be created (see docs on Creating an
Aggregate function if interested)

In the mean time, find the event based on the dates and item id. This
does assume that an item may only have one event per date.

SELECT item
, min_date
, (SELECT event
FROM events
WHERE date = min_date
AND item = items.item)
, max_date
, (SELECT event
FROM events
WHERE date = max_date
AND item = items.item)
FROM items
JOIN (SELECT min(date) AS min_date
, max(date) AS max_date
, item
FROM events
GROUP BY item) AS ev USING (item)

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Alexei Chetroi 2003-09-07 14:19:50 Re: SQL subqueries newbie help
Previous Message Alexei Chetroi 2003-09-07 11:42:31 Re: SQL subqueries newbie help