Subject | RE: [firebird-support] 4 most recent detail rows per master row |
---|---|
Author | Sasha Matijasic |
Post date | 2007-09-21T17:17:30Z |
>You havent specified what kind of layout of result set you want, so one of
> I have a master and detail table. The detail table contains a date
> column. With a single SQL query I would like to return the four most
> recent rows in the detail table for each master row. I've tried
> various ways but most resulting in a 'multiple rows in a singleton
> select error'
>
these two queries might get you what you need:
select dm.m_id, dm.dt
from d dm
where
(
dm.dt > (
select first 1 skip 4 dt
from d
where d.m_id = dm.m_id order by d.dt desc)
or
((select count(*) from d
where d.m_id = dm.m_id) <= 4)
)
and dm.dt is not null
order by dm.m_id, dm.dt desc
or
select id,
(select first 1 distinct dt from d where m_id = m.id order by dt desc),
(select first 1 skip 1 distinct dt from d where m_id = m.id order by dt
desc),
(select first 1 skip 2 distinct dt from d where m_id = m.id order by dt
desc),
(select first 1 skip 3 distinct dt from d where m_id = m.id order by dt
desc)
from m
> I'm using FB1.5I ran these queries on FB 2, but I think the syntax should be ok for 1.5
>
Performance might not be the best there is, so you might want to tweak em a
little... or rewrite them altogether... Stored procedure might be an option
too.
Sasha