1

我正在使用在 windows server 2008 R2 上运行的 oracle 11gR2

我有一张这样的桌子

   year    code    value
   ----    ----    -----
   1991      1      v1
   1991      2      v2
   1991      3      v3

   1992      1     v4
   1992      2     v5
   1992      3     v6

   ...
   2050  

代码列可以是 1 到 10。

我希望看到最终输出为(值为 1 到 10 的列)

 year    1   2   3  4 ....    10
 ----    --  --  -- --        --
 1991   v1   v2  v3 null.......null
 1992   v4   v5  v6. ...etc

如何进行旋转以获得上述格式的结果?提前致谢。

4

3 回答 3

5

一种不使用的简单方法PIVOT是使用CASE

SELECT  year,
        MIN(CASE WHEN code = 1 THEN value END) AS Col1,
        MIN(CASE WHEN code = 2 THEN value END) AS Col2,
        MIN(CASE WHEN code = 3 THEN value END) AS Col3,
        MIN(CASE WHEN code = 4 THEN value END) AS Col4,
        MIN(CASE WHEN code = 5 THEN value END) AS Col5,
        MIN(CASE WHEN code = 6 THEN value END) AS Col6,
        MIN(CASE WHEN code = 7 THEN value END) AS Col7,
        MIN(CASE WHEN code = 8 THEN value END) AS Col8,
        MIN(CASE WHEN code = 9 THEN value END) AS Col9,
        MIN(CASE WHEN code = 10 THEN value END) AS Col10
FROM YourTable
GROUP BY year

PIVOT它会是这样的:

SELECT *
FROM (SELECT year, code, value FROM YourTable) 
PIVOT (MIN(value) FOR code IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) );
于 2013-02-08T16:58:41.813 回答
3

Oracle 11g 有一个PIVOT函数可以用来将数据从行转换为列:

select *
from
(
  select year, code, value
  from yourtable
)
pivot
(
  max(value)
  for code in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10')
) piv

请参阅带有演示的 SQL Fiddle

于 2013-02-08T17:01:50.787 回答
2

在 11g 中,您可以使用pivot

SELECT *
FROM t
PIVOT (max(value) as value FOR (code) IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
于 2013-02-08T17:02:27.450 回答