直接看图吧:

把左边的表,通过一定的方式获取数据的格式为右边。

 

我的思路比较笨,如下:

①获取此表(假设这里的表名叫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

 

posted on 2012-08-26 14:45  FangMu  阅读(3794)  评论(3编辑  收藏  举报