Subject | RE: [firebird-support] Re: 4 most recent detail rows per master row |
---|---|
Author | Leyne, Sean |
Post date | 2007-09-21T20:25:24Z |
> Assuming that detail and master and joined on field called "id":Milan got it close but not quite (it wouldn't return anything for Master
>
> select d.*
> from detail d
> join master m on d.id = m.id
> where 4 > (
> select count(*)
> from detail d2
> where d2.id = m.id
> and d2.date < d.date)
which had less than 4 details)
Try this:
select
d.*
from
detail d
join master m on d.id = m.id
where
d.id in(
select
first 4
d2.id
from detail d2
where d2.id = m.id
ORDER by d2.date desc
)
Personally, I think this will perform like a wounded dog (REALLY BAD)...
So you might try using the EXECUTE BLOCK command to create an "in-line"
procedure which processed through the details, in sorted order by master
ID and other criteria you needed, and then returned up to the first 4
items per master ID, and then skipped the rest (until the Master ID
changed).
Sean