Subject Re: [firebird-support] Re: 4 most recent detail rows per master row
Author Svein Erling Tysvaer
Milan Babuskov wrote:
> Assuming that detail and master and joined on field called "id":
>
> 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)

Just another option to do the same thing (I haven't measured, but I
think it will be faster than using COUNT in a subquery):

select d.*
from detail d
join master m on d.id = m.id
where not exists(
select *
from detail d1
join detail d2 on d1.id = d2.id and d1.date < d2.date
join detail d3 on d2.id = d3.id and d2.date < d3.date
join detail d4 on d3.id = d4.id and d3.date < d4.date
where d.id = d1.id
and d.date < d1.date)

Set