Re: SQL subqueries newbie help

Поиск
Список
Период
Сортировка
Искать
От
Bruno Wolff III
Тема
Re: SQL subqueries newbie help
Дата
Msg-id
20030906154149.GA24418@wolff.to
Ответ на
Список
Дерево обсуждения
SQL subqueries newbie help Alexei Chetroi <lexoid@lexa.uniflux-line.net>
Re: SQL subqueries newbie help Rod Taylor <rbt@rbt.ca>
Re: SQL subqueries newbie help Alexei Chetroi <lexoid@lexa.uniflux-line.net>
Re: SQL subqueries newbie help Rod Taylor <rbt@rbt.ca>
Re: SQL subqueries newbie help Alexei Chetroi <lexoid@lexa.uniflux-line.net>
Re: SQL subqueries newbie help Tom Lane <tgl@sss.pgh.pa.us>
Re: SQL subqueries newbie help Bruno Wolff III <bruno@wolff.to>
On Sat, Sep 06, 2003 at 14:07:09 +0300, Alexei Chetroi  wrote:
>  Hi All,
> 
>  I need a little help regarding writing some subqueries. For example I
> have a table "items" which contains columns: itemid, description; and
> another table "events" with columns: itemid, date, event. events.itemid
> references items.itemid. Table events contains events regarding some
> itemid's from table items, so there could be multiple events regarding
> one item from items table. for example:
> 
> Table: items
> itemid    description
> 1         Lamp
> 2         Desk
> 3         HiFi
> 
> Table: events
> itemid    event        date
> 1         purchase     2003-01-01
> 1         repair       2003-01-03
> 1         repair       2003-02-05
> 2         purchase     2003-02-01
> 3         HiFi         2003-02-01
> 
>  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?

You can use group by to do this. If there were a large amount of events per
item, you might get better performance by using disctinct on and limit
in subqueries to get the max and min. That doesn't seem likely for this
problem. Distinct on would also be useful if you want to get the event
with the first and last dates.

The query you want looks something like this:
select description, min(date), max(date) from items, events where items.itemid = events.itemid group by description;

В списке pgsql-sql по дате отправления
От: Alexei Chetroi
Дата:
Сообщение: SQL subqueries newbie help
От: Rod Taylor
Дата:
Сообщение: Re: SQL subqueries newbie help
FAQ