2008-05-21

oracle行转列

在做统计分析时数据库中的表以行的形式存储,但经常会以列的形式呈现给用户。我最近做过两个功能都是这样的需求。

涉及到行转列的时候方式一般无外乎以下几种方式:

1.通过编程程序(java,pas,c#)进行遍历,形成集合。

2.如果是oracle,可以通过pl/sql,写cursor进行遍历。

3.如果是oracle,通过聚合函数。

4.如果是oracle,通过分析函数。

我遇到这样的情况经常使用3,4两种方式.我举例来说明:

数据库表example

BSC    LOGTIME        CHECKVALUE

BSC1 2008-05-18 01   1

BSC2 2008-05-18 01   2

BSC3 2008-05-18 01   3

BSC4 2008-05-18 01   1

BSC5 2008-05-18 01   3

BSC1 2008-05-18 02   4

BSC2 2008-05-18 02   5

BSC3 2008-05-18 02   1

BSC4 2008-05-18 02   4

BSC5 2008-05-18 02   1

BSC1 2008-05-18 03   1

BSC2 2008-05-18 03   1

BSC5 2008-05-18 03   1

我们要给用户呈现的内容

BSC名 1时 2时 3时 4时 5时 6时 7时 8时 9时 10时 11时 ....24时

BSC1   1    1     1   1   1    1    1 .....

BSC2  2   2      2   22   22 22 22.....

...

使用聚合函数

select BSC,

max(decode(TO_CHAR(logtime,'HH24'),1,value,null) one,

max(decode(TO_CHAR(logtime,'HH24'),2,value,null) two,

....

from example

group by BSC

使用分析函数

数据库表example

BSC    NBAO

BSC1  BSC2

BSC1 BSC3

BSC1 BSC4

BSC2 BSC1

BSC2 BSC3

BSC2 BSC4

...

要呈现的表

BSC  NBAO1 NBAO2 NBAO3 NBAO4

BSC1 BSC2   BSC3  BSC4   ...

BSC2 BSC3  BSC4 ....

使用分析函数

select BSC,

max(decode(rn,1,NBAO,null)NBAO1,

max(decode(rn,2,NBAO,null)NBAO2,

max(decode(rn,3,NBAO,null)NBAO3,

max(decode(rn,4,NBAO,null)NBAO4

from(

select BSC,NBAO,row_number() over(partition BSC order by bsc) rn

from example)

group  by BSC

.

以上使用sql语句可以实现行转列,当然,前提条件是转换后行数是固定的.

 

 

评论
elice 2008-05-22
我出写过这样的ORACLE代码,只是没有记录下来,有两种写法
发表评论

您还没有登录,请登录后发表评论

lengyue
搜索本博客
最近加入圈子
存档
最新评论