找回密码
 立即注册

QQ登录

只需一步,快速开始

WantSong

高级会员

65

主题

78

帖子

1113

积分

高级会员

积分
1113

活字格认证

WantSong
高级会员   /  发表于:2009-12-14 11:27  /   查看:6538  /  回复:0
原表test_table:

NAMETYPE
a1
b1
c1
d1
e2
f2
g2
h2
i3
j3
k3
l3
m4
n4
o4
p4

要求:

NAME1

NAME2

NAME3

NAME4

a

e

i

m

b

f

j

n

c

g

k

o

d

h

l

p

执行如下SQL即可,
select
max(decode(type,1,name,null) ) name1,
max(decode(type,2,name,null) ) name2,
max(decode(type,3,name,null) ) name3,
max(decode(type,4,name,null) ) name4
from(
select name,
row_number() over(partition   by   type   order   by   type)  rid,
type
from test_table
)t
group by rid

如果需要:

NAME1

NAME2

NAME3

NAME4

a

b

c

d

e

f

g

h

i

j

k

l

m

n

o

p

只要将type和rid替换位置即可。
select
max(decode(rid,1,name,null) ) name1,
max(decode(rid,2,name,null) ) name2,
max(decode(rid,3,name,null) ) name3,
max(decode(rid,4,name,null) ) name4
from(
select name,
row_number() over(partition   by   type   order   by   type)  rid,
type
from test_table
)t
group by type
rid是每个分组的组序号。
如果不添加goup by,则只能取到一行最大数据。

这样的SQL要求列数必须固定,因为SQL是写死的。这样的话,直接匹配需求的可能性比较小。
动态生成SQL就可以了。

0 个回复

您需要登录后才可以回帖 登录 | 立即注册
返回顶部