Pivot或Unpivot查询结果?

时间:2014-05-01 15:49:38

标签: oracle11g oracle10g oracle-sqldeveloper

我是Oracle中可用的令人困惑的pivot和unpivot运算符的新手。有人可以帮助我调整这样的查询结果吗?

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

);

结果是这样的:

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

我需要这样的事情:

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

请指导我如何实现这一目标。

1 个答案:

答案 0 :(得分:0)

试试这个:

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));