Só é possível com sql dinâmico, pois o número de colunas na cláusula group by é variável. Por exemplo, com uma função:
create or replace
function sum_cash_transactions ( p_threshold_type varchar2) return number
is
v_result NUMBER;
begin
execute immediate ' select max( sum_amount)
from( select sum(amount) as sum_amount
from cash_transactions
group by ' || p_threshold_type || ' )'
into v_result;
return v_result;
end;
/
e depois
select threshold_id
from thresholds
where threshold_amount < sum_cash_transactions(threshold_type);
EDITAR devido a novos requisitos:
CREATE OR REPLACE package pkg AS
TYPE res_rec_type IS RECORD (
threshold_id VARCHAR2(200)
, Tran_inst_id NUMBER(10,0)
, sum_amount NUMBER(22)
);
TYPE res_tab_type IS TABLE of res_rec_type;
FUNCTION f1 RETURN res_tab_type PIPELINED;
END;
/
CREATE OR REPLACE PACKAGE BODY pkg AS
FUNCTION f1 RETURN res_tab_type PIPELINED
IS
CUR SYS_REFCURSOR;
v_rec res_rec_type;
BEGIN
FOR treshold in ( SELECT Threshold_id, Threshold_type, Threshold_amount FROM thresholds)
LOOP
OPEN CUR FOR 'SELECT ' || threshold.Threshold_id || ', tTran_inst_id, s FROM (SELECT tTran_inst_id, SUM(AMOUNT) OVER (PARTITION BY ' || p_Threshold_type || ') as s from cash_transactions ) WHERE s > ' || treshold.Threshold_amount ;
LOOP
FETCH cur INTO v_rec;
EXIT WHEN cur%NOTFOUND;
pipe row(v_rec);
END LOOP;
END LOOP;
CLOSE cur;
RETURN;
END;
END;
/
SELECT * form table(pkg.f1);