社区里有人提问一个行转列的应用,在SQLServer中都是用Case的,我随便答了一下,由于是非固定行,有网友给我发消息问怎么实现,详细来说一下。
相关联接
http://community.csdn.net/Expert/topic/3417/3417326.xml?temp=.8530084
Answer:
表
F1 F2
jack book1
jack book2
jack book3
mary book4
mary book5
...
转化为
F1F2F3F4F5
jack book1 book2 book3
mary book4 book5
billy book6 book7
--------------------------------------------
测试过程:
--------------------------------------------
create table Test
(F1 char(10),
F2 char(10))
--测试表
insert into Test
select 'jack' F1,'book1' F2
union
select 'jack' F1,'book2' F2
union
select 'jack' F1,'book3' F2
union
select 'Mary' F1,'book4' F2
union
select 'Mary' F1,'book5' F2
union
select 'Mike' F1,'book1' F2
union
select 'Mike' F1,'book5' F2
union
select 'Mike' F1,'book7' F2
union
select 'Mike' F1,'book9' F2
--插入数据
select id=identity(int,0,1),f1,f2 into #t from test
select a.f1,a.f2,a.id,cc ,N=
case when (id>cc) then cast(id-cc-minn+1 as Char(10))
when (id<=cc) then cast(id+1 as Char(10))
end
into #Temp
from #t a,
(select f1,cc,minn from
(select f1,count(*)as cc,min(id)-count(*) as minn from #t group by f1) t)b
where a.f1=b.f1
--构造两个临时表,由于要用到行号,所以必须要第一个临时表,第二个可以不用
select * from #Temp
--这个表笔原来的多一个字段,每个人的第n条记录
DECLARE @SQL VARCHAR(8000)
SET @SQL='SELECT f1 姓名'
SELECT @SQL= @SQL+ ',MIN(CASE WHEN N = ''' + N + ''' THEN F2 END) [F' + N + ']' FROM (SELECT DISTINCT N FROM #Temp) A
SET @SQL=@SQL+' FROM #Temp GROUP BY F1'
EXEC (@SQL)
--一条动态SQL语句
drop table #t
drop table #Temp
drop table Test
/*
jack book1 1
jack book2 2
jack book3 3
Mary book4 1
Mary book5 2
Mike book1 1
Mike book5 2
Mike book7 3
Mike book9 4
--------Temp表数据*/
/*
jack book1 book2 book3 NULL
Mary book4 book5 NULL NULL
Mike book1 book5 book7 book9
--------最终结果*/