Oracle
 SQL >> Datenbank >  >> RDS >> Oracle

Eine Abfrage ausführen, wenn die GROUP-BY-Spalte zur Laufzeit variiert

Da die Gruppierungsspalte erst zur Ausführungszeit bekannt ist, kann statisches SQL sie nicht ausdrücken – dynamisches SQL ist die einzige Option. In eine Funktion verpackt bleiben die Aufrufstellen übersichtlich:

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; /

was sich dann natürlich in einer Abfrage liest:

select threshold_id from thresholds where threshold_amount < sum_cash_transactions(threshold_type);

Bearbeitung für die überarbeiteten Anforderungen: Eine pipelined Funktion kann statt einer einzelnen Zahl eine ganze Ergebnismenge zurückgeben.

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);

Welche Form Sie auch wählen, validieren oder whitelisten Sie den interpolierten Bezeichner – ein direkt in dynamisches SQL eingefügter Spaltenname ist ein Injection-Punkt.