表A字段与内容如下:都是varchar类型sName     sValue
001       a
001       b
002       a
002       a
002       b============================
要得到如下结果,按sName分组:001       ab
002       aab请问SQL语句怎么写?谢谢.

解决方案 »

  1.   

    你只能自己写一个函数来处理所有sName相同的sValue 得到你想要的那列值了.这用select 和group by 可是完成不了的.你要的那可是数据按字符拼接的新值.
      

  2.   

    http://topic.csdn.net/u/20080617/14/75efd86b-964e-42dd-a2ff-3f49935d7b54.html
      

  3.   

    declare @t table(sName varchar(10), sValue varchar(10))insert into @t values('001','a')
    insert into @t values('001','b')
    insert into @t values('002','a')
    insert into @t values('002','a')
    insert into @t values('002','b')select * from @t-- select sname, sum(svalue)
    -- from @t
    -- group by sname可惜不支持,自己动手吧
      

  4.   

    有些数据库才有直接的函数.比如MySQL有. 没有的话要自己写个函数了.MySQL里有个group_concat函数.用法: select sName,group_concat(sValue) from 表A group by sName;
      

  5.   

    create function fn(@IDA varchar(8))
    returns varchar(128)
    as
    begin
        declare @Fee varchar(128)
        set @Fee=''
        select @Fee=@Fee+svalue+cast(Fee as varchar) from a where IDA=@IDA
        set @Fee=rtrim(@Fee)
        return @Fee
    endselect *, Fee=dbo.fn(sname) from a A
      

  6.   

    以上仅仅适合在MS SQL Server时的情况。
      

  7.   

    这个问题我以前也想过
    只用一条SQL语句不太好弄,后来用游标
      

  8.   

    if object_id('tb') is not null
       drop table tb
    go
    create table tb(sName varchar(10),sValue varchar(10))
    go
    insert into tb
    select '001','a' union all
    select '001','b' union all
    select '002','a' union all
    select '002','a' union all
    select '002','b'
    go
    if object_id('uf_sumvalue') is not null
       drop function uf_sumvalue
    go
    create function uf_sumvalue(@sName varchar(10))
    returns varchar(100)
    as
    begin
      declare @str varchar(100)
      select @str=isnull(@str,'')+sValue from tb where sName=@sName
      return @str
    end
    go
    select sName,sValue=dbo.uf_sumvalue(sName) from tb group by sName