直接看圖吧:
把左邊的表,通過一定的方式獲取數據的格式為右邊。
我的思路比較笨,如下:
①獲取此表(假設這里的表名叫tbtest)的所有distinct a1的數據放到一個臨時表#a1里。
②獲取第一個a1的字段,從tbtest中獲取相匹配的a2,把這些a2放到一個臨時表#a2里。
③一個一個從#a2獲取值,進行拼接放到變量字段里。
④把此時的a1和拼接好的字段存入結果表#tbresult里。
⑤再獲取第二個a1的字段,重復②到④。
sql代碼如下:
1 declare @a1sum int --a1總數
2 declare @a1index int --a1索引
3 declare @a2sum int --a2總數
4 declare @a2index int --a2索引
5 declare @content nvarchar(100) --a2內容
6 declare @tmpa1 nvarchar(10) --臨時a1的值
7 set @a1index=1
8
9 select top 0 * into #tbresult from tbtest --存儲結果的表 #tbresult,可以根據需要自定義字段類型
10 select distinct a1 into #lsa1 from tbtest --獲取唯一a1的數據
11 select a1,ROW_NUMBER() over (order by a1 ) as a1index into #a1 from #lsa1 --存儲全部a1數據的臨時表 #a1
12
13 select @a1sum=COUNT(1) from #a1 --a1的總數
14 while(@a1index<=@a1sum) --根據當前a1的序列是否小於a1總數。a1字段一個一個獲取
15 begin
16 set @content=''
17 set @a2index=1
18 select @tmpa1=a1 from #a1 where a1index=@a1index
19 select @a2sum=COUNT(a2) from tbtest where a1=@tmpa1
20 select a2,ROW_NUMBER() over (order by a1) as xl into #tba2 from tbtest where a1=@tmpa1--儲存a2的臨時表 #tba2
21 while(@a2index <= @a2sum)--一個一個獲取a2
22 begin
23 select @content+=RTRIM(a2) from #tba2 where xl=@a2index
24 set @a2index=@a2index+1
25 end
26 set @a1index=@a1index+1 --獲取下一個a1的序列
27 insert into #tbresult values(@tmpa1,@content) --添加到臨時表里
28 drop table #tba2 29 end
30
31 select * from #tbresult 32 drop table #lsa1 33 drop table #tbresult 34 drop table #a1