This is a sample of bill table: (billnr is not unique. The combination of renr,filnr, kassanr is unique)
id   renr(billnr)   filnr(store)       kassanr(cashier)     price  res_nr(reservation)        
10        1             2                 3                   10          100
11        1             2                 3                   15          null
12        1             2                 3                   6           null   
13        1             2                 4                   120         101
I need the sum(price) for unique combination of renr,filnr, kassanr if they have resnr 100. That means : 10+15+6 = 31
I have this query:
select sum(rk.price) 
from bill rk, 
     (select rk1.renr, rk1.filnr, rk1.kassanr from bill rk1 where rk1.res_nr = :IN_n_resnr)  tr
where rk.filnr = tr.filnr 
      and rk.kassanr = tr.kassanr 
      and rk.renr = tr.renr;
When I execute this query, it's take only 7 sec and this is OK! But When I write this in a function, the function takes 21 sec and I can't understand why?!
CREATE OR REPLACE FUNCTION FUN_TEST (IN_n_resnr in number) return number
is
  v_return    number := null;      
begin   
         select sum(rk.price) into v_return
         from bill rk, 
              (select rk1.renr, rk1.filnr, rk1.kassanr from bill rk1 where rk1.res_nr = :IN_n_resnr)  tr
         where rk.filnr = tr.filnr 
         and rk.kassanr = tr.kassanr 
         and rk.renr = tr.renr;              
  return(v_return);        
end;
I tried to write the function with WITH CLAUSE. But that takes 21 sec too.
with t_resnr as 
         (select rk1.renr, rk1.filnr, rk1.kassanr from bill rk1 where rk1.res_nr = IN_n_resnr)
         select sum(rk.price) into v_return
         from bill rk, 
              t_resnr tr   
         where rk.filnr = tr.filnr 
         and rk.kassanr = tr.kassanr 
         and rk.renr = tr.renr;
 
     
    