使用sql pivot

时间:2013-02-08 16:55:35

标签: sql oracle11g pivot

我正在使用在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

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

3 个答案:

答案 0 :(得分: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) );

答案 1 :(得分: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 with Demo

答案 2 :(得分:2)

在11g中,您可以使用pivot

SELECT *
FROM t
PIVOT (max(value) as value FOR (code) IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10))