Subject RE: [firebird-support] Re: 4 most recent detail rows per master row
Author Leyne, Sean
Sasha,

> I guess it is easier to explain in sql than in english, so let me try
that
> way.
>
> create table master(id integer);
> create table detail(id integer, dt date);

You are missing the Master ID...

You need the following:

create table detail(id integer, MID Integer, dt date);
commit;
insert into master(id) values(1);
insert into detail(id, MID, dt) values (1, 1, '2007-09-01');
insert into detail(id, MID, dt) values (2, 1, '2007-09-02');
insert into detail(id, MID, dt) values (3, 1, '2007-09-03');
insert into detail(id, MID, dt) values (4, 1, '2007-09-04');
insert into detail(id, MID, dt) values (5, 1, '2007-09-05');
commit;

Then the query:

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.mid = d.mid
order by d2.dt desc
)

> It returns ALL five rows. Why? Because it is equivalent to this:

Mine returns 4 rows.


Sean