Skip to content
Advertisement

Multi-Group Unpivot in Oracle SQL returns incorrect number of rows

I have the table below:

and the following records:

And I’m currently using the query below:

and below are the results:

However, I would want to use UNPIVOT to have the below result:

I tried the below query but i am getting incorrect values in the sum:

below are the results:

If i remove the aggregates, 20 records are being fetched, 4 times the expected results:

It seems it’s doing a Merge Join Cartesian with itself:

Do I need to Add more conditions to the UNPIVOT?

Advertisement

Answer

The main issue is that you’re unpivoting three times, and aggregating at the wrong level – aggregation shouldn’t really be necessary at all, at least with the sample data.

You also need to exclude some of the values your current query returns – the functional amounts when functional box is null.

I think this non-union query gets only the data you want:

which gets:

And you can then unpivot that, with a single command:

which gets:

db<>fiddle

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