读书人

结果集变形有关问题

发布时间: 2012-12-18 12:43:41 作者: rapoo

结果集变形问题
有这样的结果集(id不是主键,f2为字符型)
---------------
id f1 f2
1 1 x
1 2 y
1 3 z

希望变形为
id f2_1 f2_2 f2_3
1 x y z

其实已经得到一个中间结果
id f2_1 f2_2 f2_3
1 x '' ''
1 '' y ''
1 '' '' z

请问应该怎么办?




[最优解释]

select id,
f2_1=max(case f1 when 1 then f2 end),
f2_2=max(case f1 when 2 then f2 end),
f2_3=max(case f1 when 3 then f2 end)
from tc
group by id
[其他解释]
对中间结果,不要用'',换成null,并且在生成中间结果时,用select id,max(f2_1),max(f2_3),max(f2_3) from xxx group by id
就可以实现你要的结果。由于你已经有中间结果了,而且我不知道是不是动态的,所以就懒的写了,
[其他解释]
在使用一个聚集函数,max即可
[其他解释]
又学会了一个函数,谢谢!

读书人网 >SQL Server

热点推荐