sql语句让相同的id的内容合并
作者/zhlyyea 时间/2007-11-5 14:38:00 类别/技术心得 查看/
 发表评论 
标签:学习
面试题:sql语句让相同的id的内容合并

/*   
  有表tb,   如下:   
  id         txt   
  -----   ------   
  1           a  
  1           b  
  1           c
  2           d
  2           e  
  3           f
    
  需要得到结果:   
  id           values   
  ------   -----------   
  1             a,b,c   
  2             d,e
  3             f   
    
  即:   group   by   id,   求   txt   的和(字符串相加)   
  */   
    
  create   table   tb(id   int,txt   varchar(100))   
  go   
  insert   into   tb   
  select   1,'a'   union   all   
  select   1,'b'   union   all   
  select   1,'c'   union   all   
  select   2,'d'   union   all   
  select   2,'e'   union   all   
  select   3,'f'   
    
  go   
  --写一个聚合函数:   
  create   function   dbo.fn_Merge(@id   int)   
  returns   varchar(8000)   
  as   
  begin   
        declare   @r   varchar(8000)   
        set   @r=''   
        select   @r=@r+','+txt   from   tb   where   id=@id   
        return   stuff(@r,1,1,'')   
  end   
  go   
    
  --   调用函数   
  select   id,   dbo.fn_Merge(id)   as   txt   from   tb   group   by   id   
        
  go   
  drop   table   tb   
  drop   function   fn_Merge
查看该用户更多文章>>