prabhakar prabhakar - 29 days ago 6
SQL Question

Dynamic pivot in oracle sql

... pivot (sum(A) for B in (X))

Now B is of datatype varchar2 and X is a string of varchar2 values separated by commas.

Values for X are select distinct values from a column(say CL) of same table. This way pivot query was working.

But the problem is that whenever there is a new value in column CL I have to manually add that to the string X.

I tried replacing X with select distinct values from CL. But query is not running.

The reason I felt was due to the fact that for replacing X we need values separated by commas.

Then i created a function to return exact output to match with string X. But query still doesn't run.

The error messages shown are like "missing righr parantheses", "end of file communication channel" etc etc.

I tried pivot xml instead of just pivot, the query runs but gives vlaues like oraxxx etc which are no values at all.

Maybe I am not using it properly.

Can you tell me some method to create a pivot with dynamic values?

Answer

You can't put a non constant string in the IN clause of the pivot clause.
You can use Pivot XML for that.

From documentation:

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

It should look like this:

select xmlserialize(content t.B_XML) from t_aa
pivot xml(
sum(A) for B in(any)
) t;

You can also have a subquery instead of the ANY keyword:

select xmlserialize(content t.B_XML) from t_aa
pivot xml(
sum(A) for B in (select cl from t_bb)
) t;

Here is a sqlfiddle demo