随笔 - 118  文章 - 0 评论 - 341 阅读 - 299万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

直接看图吧:

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

 

我的思路比较笨,如下:

①获取此表(假设这里的表名叫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   FangMu  阅读(3803)  评论(3编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示