有一表:table
有以下三個字段:id,   name,       code
4 AA S2Z
4 AA WUM
13 DD S2P
13 DD S4I
13 DD WMA
13 DD ZHB
13 DD ZMA
13 DD M4I
15 EE M4P
15 EE M4S
13 EE S4Q要求得到如下結果:id,   name,       code4 AA S2Z,WUM
13 DD S2P,S4I,WMA,ZHB,ZMA,M4I
15 EE S4Q,M4P,M4S我想用
select id,   name,       code
from  table
group by id,name sum(code)
但這個字段CODE是字符型.
所以...最好不要用游標.
  

解决方案 »

  1.   

    --先贴一下测试数据
    --准备用自定义函数, 这样只可以吗?
    if object_id('ta') is not null drop table ta
    go
    create table ta( id int, name varchar(10), code varchar(10))
    insert ta  select 4, 'AA', 'S2Z'
    union  all select 4, 'AA', 'WUM'
    union  all select 13, 'DD', 'S2P'
    union  all select 13, 'DD', 'S4I'
    union  all select 13, 'DD', 'WHA'
    union  all select 13, 'DD', 'ZHB'
    union  all select 13, 'DD', 'ZMA'
    union  all select 13, 'DD', 'M4I'
    union  all select 15, 'EE', 'M4P'
    union  all select 15, 'EE', 'M4S'
    union  all select 13, 'EE', 'S4Q'
      

  2.   

    --接测试数据
    if object_id('codeall') is not null drop function dbo.codeall
    go
    create function dbo.codeall(@id int, @name varchar(10))
    returns varchar(1000)
    as
    begin
     declare @str varchar(1000)
     set @str=''
     select @str=@str+','+code from ta 
     where id=@id and name=@name
     set @str=stuff(@str, 1, 1, '')
     return @str
    end
    goselect id, name, code=dbo.codeall(id, name)
    from (select id, name from ta group by id, name)t