-- Set your start and end dates SET start_date = '2023-01-01'; SET end_date = '2023-10-31';
-- Set the months you're interested in SET target_months = '7,8,9,10';
-- Generate the dynamic SQL query using JavaScript SELECT EXECUTE IMMEDIATE ( SELECT 'SELECT ID, ' || LISTAGG('SUM(CASE WHEN DATE_TRUNC(''MONTH'', TO_DATE(received_month, ''YYYY-MM-DD'')) = TO_DATE(''2023-' || m || '-01'', ''YYYY-MM-DD'') THEN Volume ELSE 0 END) AS total_volume_month' || m, ', ') WITHIN GROUP (ORDER BY m) || ' FROM transactions GROUP BY ID' FROM TABLE(FLATTEN(INPUT => SPLIT(:target_months, ','))) AS months );