retrieving primary key for row with MIN function

Поиск
Список
Период
Сортировка
От Marcin Krol
Тема retrieving primary key for row with MIN function
Дата
Msg-id 49F84856.5010400@gmail.com
обсуждение исходный текст
Ответы Re: retrieving primary key for row with MIN function  (Scott Marlowe <scott.marlowe@gmail.com>)
Re: retrieving primary key for row with MIN function  (Richard Broersma <richard.broersma@gmail.com>)
Re: retrieving primary key for row with MIN function  (Erick Papadakis <erick.papa@gmail.com>)
Список pgsql-general
Hello everyone,

I need to retrieve PK (r.id in the query) for row with
MIN(r.start_date), but with a twist: I need to select only one record,
the one with minimum date.

Doing it like this does not solve the problem:

SELECT h.id AS host_id, MIN(r.start_date) AS reservation_start_date,
r.id AS reservation_id
FROM hosts h
LEFT OUTER JOIN reservation_hosts rh ON rh.host_id = h.id
LEFT OUTER JOIN reservation r ON r.id = rh.reservation_id AND
(r.start_date, r.end_date) OVERLAPS ('2009-04-29'::date, '2010-04-29'::date)
GROUP BY h.id, r.id
ORDER BY reservation_start_date ASC

I have to use either GROUP BY r.id or use MIN(r.id). MIN(r.id) doesn't
select the id from the row with corresponding MIN(r.start_date), so it's
useless, while GROUP BY r.id produces more than one row:

host_id    reservation_start_date    reservation_id
361     2009-05-11              38
361     2009-05-17              21

I need to select only row with reservation_id = 38.

I would rather not do subquery for every 'host' record, since there can
be a lot of them...

Regards,
mk



В списке pgsql-general по дате отправления:

Предыдущее
От: Peeyush Jain
Дата:
Сообщение: Issue with SSAS
Следующее
От: Richard Broersma
Дата:
Сообщение: Re: triggers and execute...