Desired output with given table data

混江龙づ霸主 提交于 2019-12-01 06:14:41

问题


Hi I have a table test its structure is given below:

**Testing**

  PK    C1    c2  
 ---------------
 1      v11  v12
 2      v21  v23
 3      v31  v32

Now I need to query this table (testing) such that I get the below output.

 Pk  Key value 
---------------
 1    c1    v11
 1    c1    v12
 2    c2    v21
 2    c2    v22
 3    c3    v31
 3    c3    v32

Can this been possible with sql query in Oracle 11g ,Is it possible with PIVOT feature in 11g?


回答1:


No, it can't be done with PIVOT, but it can be done with UNPIVOT:

SELECT
  Pk,
  "Key",
  value
FROM Testing
UNPIVOT (
  value FOR "Key" IN (C1, C2)
)

And when UNPIVOT is unavailable, I often unpivot like this:

SELECT
  t.Pk,
  x."Key",
  CASE x."Key"
    WHEN 'C1' THEN t.C1
    WHEN 'C2' THEN t.C2
  END AS value
FROM Testing t
CROSS JOIN (
  SELECT 'C1' AS "Key" FROM DUAL UNION ALL
  SELECT 'C2' FROM DUAL
) x


来源:https://stackoverflow.com/questions/9408622/desired-output-with-given-table-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!