Sum and Group by dynamically in Oracle Sum and Group by dynamically in Oracle oracle oracle

Sum and Group by dynamically in Oracle


Something like this may well work for you (I'm not 100% certain because your question is very vague)

SELECT  CASE WHEN :p1 = 0 THEN p1 ELSE NULL END AS p1,  CASE WHEN :p2 = 0 THEN p2 ELSE NULL END AS p2,  CASE WHEN :p3 = 0 THEN p3 ELSE NULL END AS p3,  CASE WHEN :p4 = 0 THEN p4 ELSE NULL END AS p4FROM  yourTableGROUP BY  CASE WHEN :p1 = 0 THEN p1 ELSE NULL END,  CASE WHEN :p2 = 0 THEN p2 ELSE NULL END,  CASE WHEN :p3 = 0 THEN p3 ELSE NULL END,  CASE WHEN :p4 = 0 THEN p4 ELSE NULL END

Be aware, however, that SQL often performs quite poorly with this type of query.

For each and every fixed query, a separate plan is compiled. The algorithm use to generate the results is fixed in place at that point. It is not re-compiled when your parameters are changed.

This is important because, depending on your indexes, GROUP BY p1, p2 could results in a fundamentally different plan from using GROUP BY p3, p4.

Because of that it can often be much more performant to re-generate the SQL statement in code.

Rather than asking SQL to use the parameters to pick which fields are aggregated, use the parameters to write a brand new SQL statement, and execute that new SQL statement instead.


if you want to use something like group concat in mysql this can help Is there an Oracle SQL query that aggregates multiple rows into one row?


This problem can be solved by using dynamic SQL. In dynamic SQL you can first construct your select statement base on the input parameters and then execute the query using e.g. EXECUTE IMMEDIATE. Please read the oracle documentation on how to use dynamic SQL.