zoukankan      html  css  js  c++  java
  • Sql 合并同一列的非数值字段

    直接看图吧:

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

     

    我的思路比较笨,如下:

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

     

  • 相关阅读:
    [转]Modernizr的介绍和使用
    java动态代理使用详解
    ajax上传文件以及使用中常见问题处理
    cmd下查询端口占用以及根据进程id名称结束进程
    水平居中 垂直居中
    inline-block和float
    一起入门前端(三)
    一起入门前端(二)
    一起入门前端(一)
    WPF初学——自定义样式
  • 原文地址:https://www.cnblogs.com/polk6/p/2657362.html
Copyright © 2011-2022 走看看