oracle - Select sum query does not work while implemented in a function/procedure -
i came cross problem when using 2 sum() in function called procedure. results inputted came separate. following tables, function , procedure tried. p.s. - works fine when there single sum(x).
drop table match; create table match (m_id varchar2 (4) not null, ht_id varchar2 (4), at_id varchar2 (4), p_f number (3), p_a number (3)); insert match values ('m01','t1', 't2', 2, 0); insert match values ('m02','t1', 't2', 1, 1); insert match values ('m03','t1', 't2', 0, 2); insert match values ('m04','t1', 't2', 0, 2); insert match values ('m05','t2', 't1', 2, 0); insert match values ('m06','t2', 't1', 0, 2); insert match values ('m07','t2', 't1', 1, 2); insert match values ('m08','t2', 't1', 0, 2);
temp table (where results stored):
drop table results; create global temporary table results (ht_id varchar2 (5), final number (2)) on commit preserve rows; insert results values('t1', null); insert results values('t2', null); insert results values('t3', null); insert results values('t4', null); insert results values('t5', null);
query applied:
select sum(case when ht_id='t1' p_f else 0 end) + sum(case when at_id='t1' p_a else 0 end) match;
returns result of 9, applied select query in function , made procedure call function , store results in temp table. although result of sum done in function comes separate (e.g. 6 t1 , 3 t2, although 9 points should t1 alone).
ht_id final ----- ---------- t1 3 t2 6 t3 0 t4 0 t5 0
how can retain same result query , input them temp table? like below:
ht_id final ----- ---------- t1 9 t2 0 t3 0 t4 0 t5 0
this tried in regards of function , procedure:
drop function resultsfinal; create or replace function resultsfinal(i_ht_id results.ht_id%type) return varchar2 v_results_final results.final%type; begin select sum(case when ht_id='t1' p_f else 0 end)+ sum(case when at_id='t1' p_a else 0 end) v_results_final match ht_id = i_ht_id; if v_results_final null v_results_final := 0; end if; return v_results_final; end; /
the procedure:
create or replace procedure finalscores cursor c_results select ht_id results; v_ht_id results.ht_id%type; v_results_final results.final%type; begin open c_results; loop fetch c_results v_ht_id; exit when c_results%notfound; v_results_final := resultsfinal(v_ht_id); update results set final = v_results_final ht_id = v_ht_id; end loop; close c_results; end; /
execute finalscores;
thanks in advance.
select sum(case when ht_id=i_ht_id p_f else 0 end) + sum(case when at_id=i_ht_id p_a else 0 end) v_results_final match;