用函数及sql语句合并字符串!

    技术2022-05-11  76

    有表內容﹕ 編號 內容 A    abc A    aaa A    dddd B    1223 B    fkdjfd ....

    實現結果﹕A   abc,aaa,ddddB   1223,fkdjfd要求用一條SQL實現﹐如﹕select sum(內容) from table group by 編號--该问题,写一个合并函数,后,分组合并既可!--测试数据create Table 表(編號 varchar(20),內容 varchar(20))insert 表 select 'A','abc'union all select 'A','aaa'union all select 'A','dddd'union all select 'B','1223'union all select 'B','fkdjfd'

    --处理分组合并函数学Create Function JoinStr(@SNO as varchar(20))returns varchar(200)begindeclare @s as varchar(8000)set @s=''select @s=@s+','+ltrim(rtrim(內容)) from(select 內容 from 表 where 編號=@SNO)Aset @s=stuff(@s,1,1,'')return  @send

    --查询语句select 編號,dbo.JoinStr(編號) as 内容 from 表 group by 編號--测试结果:編號     内容A abc,aaa,ddddB 1223,fkdjfd

     

    ======用SQL解决方法:

    http://community.csdn.net/Expert/topic/4323/4323684.xml?temp=.1937982

    table1: News-----------------------------------------------------------rsid     title     subject     class1        天空蓝了  ....        小学文章-----------------------------------------------------------

    table2: ModifyLogs-----------------------------------------------------------rsid     NewsID    Name        Memo1        1         张三        有一些错别字,还需要修改2        1         张四        成语和一些词语用错-----------------------------------------------------------

    我现在需要用一条语名查询出这样的结果-----------------------------------------------------------Unid    Title        subject   Class        Name1       天空蓝了     .....     小学文章     张三,张四

    -----------------------------------------------------------就是说把只要是修改了该文章的老师的名称显示在一个字段中.....请问如何实现......

    declare @tname varchar(4000)set @tname=''select @tname=@tname +rtrim(b.Name)+',' from ModifyLogs b left join News a on a.rsid=b.NewsIDset @tname=left(@tname,len(@tname)-1)print @tname

    select distinct a.rsid as Unida,a.Title,a.subject,a.Class,@tname as name from News aleft join ModifyLogs b on a.rsid=b.NewsID

     

    最新回复(0)