简体   繁体   中英

Sum and Group by dynamically in Oracle

I have a requirement in which there are four parameters. p1,p2,p3,p4. User can enter any of these either single or combinations.I want to display only the columns which he enters by summing and grouping.Other columns should be excluded.How can i do this?

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 p4
FROM
  yourTable
GROUP 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.

如果你想在mysql中使用类concat之类的东西,这可以帮助是否有一个Oracle SQL查询将多行聚合成一行?

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 eg EXECUTE IMMEDIATE. Please read the oracle documentation on how to use dynamic SQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM