Example of an Oracle PIVOT clause with subquery

Lukas Eder picture Lukas Eder · Jan 6, 2012 · Viewed 68.6k times · Source

Oracle's definition of the PIVOT clause specifies that there is a possibility to define a subquery in the IN clause. A fictional example of what I would imagine this to be is this

... PIVOT (AVG(salary) FOR (company) IN (SELECT DISTINCT company FROM companies))

With that, however, I get an ORA-00936: Missing expression error. Unfortunately, errors from this new PIVOT clause are usually rather cryptic. Can anyone give me a good example of how a subquery can be used in the IN clause of the PIVOT clause?

Answer

Lukas Eder picture Lukas Eder · Jan 6, 2012

Apparently, I was too lazy to read to the end of the documentation... Further down, the documentation states:

subquery A subquery is used only in conjunction with the XML keyword. When you specify a subquery, all values found by the subquery are used for pivoting. [...]

This will work

PIVOT XML (AVG(salary) FOR (company) IN (SELECT DISTINCT company FROM companies))

See the full documentation

http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_10002.htm#CHDFAFIE