Question

I am new to the confusing pivot and unpivot operators available in Oracle. Can someone help me pivot the results of a query like this?

SELECT * FROM
(
    SELECT
    ROUND(((SELECT COUNT(*) FROM TABLE_X WHERE X = 1) / (SELECT (COUNT(*)) FROM TABLE_X) * 100))AS X_FIELD,
    ROUND(((SELECT COUNT(*) FROM TABLE_Y WHERE Y = 1) / (SELECT (COUNT(*)) FROM TABLE_Y) * 100))AS Y_FIELD FROM DUAL

);

Results are something like this:

X_FIELD        Y_FIELD
----------     ----------
37             26

And I need something like this:

FIELDS         PERCENTAGE
----------     ----------
X_FIELD        37 
Y_FIELD        26

Please guide me how to achieve this.

Was it helpful?

Solution

Try this:

WITH temp_result AS
  (SELECT ROUND((
    (SELECT COUNT(*) FROM TABLE_X WHERE X = 1) /(SELECT (COUNT(*)) FROM TABLE_X) * 100))AS X_FIELD,
    ROUND(((SELECT COUNT(*) FROM TABLE_Y WHERE Y = 1) /(SELECT (COUNT(*)) FROM TABLE_Y) * 100))AS Y_FIELD
  FROM DUAL
  )
SELECT *
FROM temp_result UNPIVOT INCLUDE NULLS ( VALUE FOR COL IN (X_FIELD,Y_FIELD));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top