Subject [firebird-support] Re: Nested 'for select's on same table & 'leave' problem
Author Svein Erling Tysvær
>SELECT FIRST 1 ADATE, sum(VOL)
>FROM PRICES
>where FK_COMPANY = :COMPANY_PK and ADATE <= :aDate
>GROUP BY 1
>HAVING sum(VOL) >= :targetVol
>order by ADATE desc
>into :bDate, :vol

Whoops, that would sum ALL records before :aDate for the company. Of course I meant:

SELECT FIRST 1 ADATE, (select sum(VOL) FROM PRICES B
where b.FK_COMPANY = a.FK_COMPANY and b.ADATE BETWEEN a.ADATE and :aDate)
FROM PRICES A
where a.FK_COMPANY = :COMPANY_PK and a.ADATE <= :aDate
and (select sum(VOL) FROM PRICES B
where b.FK_COMPANY = a.FK_COMPANY and b.ADATE BETWEEN a.ADATE and :aDate)>= :targetVol
order by ADATE desc
into :bDate, :vol

Of course, for this to work, there should only be one record for each date for each company (it's doable even if this isn't the case, just requires a bit more care).

HTH,
Set