社區裡有人提問一個行轉列的應用,在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
...
轉化為
F1 F2 F3 F4 F5
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
--------最終結果*/