Skip to content
Advertisement

Combining MAX and SUM in an Oracle ROLLUP

Here’s my SQL:

The output looks like this:

I was expecting it to look like this:

In other words, I was expecting the rollup to sum up the maximum weights of each food instead of taking the maximum of all the maximums in the food-type category.

I do have a solution of sorts, but it means having to add an additional layer of SQL-statement nesting:

Is there a way to do it without the extra nesting?

Of course, this example is significantly simplified from my real-world situation, which is why I’m trying to find a way to reduce the number of lines of code. Reducing a SQL statement by 60 lines of code significantly eases its maintenance in the long term.

Advertisement

Answer

Revisiting this after a few days. It can be done like this:

To be honest, I’m not 100% sure I like this answer either. Depending on the context and from a maintenance point of view, the CASE-WHEN statement is more difficult to understand than the multi-level SELECT.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement