I have a fucntion pb(IDCODE,0) running it with IDCODE=320 gives this sample data:
select *
from pb(320,0)
logid entrydate qty
1 1.10.17 5
2 1.10.17 6
3 1.10.17 5
4 1.10.17 -3
5 2.10.17 6
6 3.10.17 -100
*it actually gives more rows (like 20000) but I reduced it for the example
pb is a very heavy function but in simple terms it shows activities based on their order.
I want to find the entrydate of the first occurrences of qty<0 after the last row of qty>0.
In order to do that I need to do something like this:
Select Min(logid) where qty<0 and logid>(select max(logid) where qty>=0)
In the above sample the requested result is 3.10.17
Because:
logid=5 is max(logid) where qty>=0
and
logid=6 is Min(logid) where qty<0 and logid>(select max(logid) where qty>=0)
which in fact is : Select Min(logid) where qty<0 and logid>5
So I wrote the following query:
select entrydate
from pb(320,0)
where logid= ( SELECT min(logid)
FROM pb(320,0)
where qty<0 and logid>(SELECT coalesce(max(logid),0)
FROM pb(320,0)
WHERE qty >= 0))
This works great but it's 3 times that I call the function pb(320,0).
It's huge time consuming and needless to say that I actually run this query on many IDCODES (like 214) so pb(IDCODE,0) actually runs 214*3 this is horrible.
What can I do?
SELECT max() INTO maxValue...) and using the variable in a more simple query. Just my two cents.