将表    ---------------- 
        | 编号|  姓名   |
        ----------------
        |01   |  张     |
        ----------------
        |01   |  王     |
        ----------------
        |02   |  李     |
        ----------------
转化成表---------------- 
        | 编号|  姓名   |
        ----------------
        |01   |  张,王 |
        ----------------
        |02   |  李     |
        ----------------
SQL语句如何写,多谢

解决方案 »

  1.   

    一个例子:
    -------------------------------------------------------------------------
    --生成测试数据
    create table 表(部门 int,人员 varchar(20))
    insert into 表 select 1,'张三'
    insert into 表 select 1,'李四'
    insert into 表 select 1,'王五'
    insert into 表 select 2,'赵六'
    insert into 表 select 2,'邓七'
    insert into 表 select 2,'刘八'
    go--创建用户定义函数
    create function f_str(@department int)
    returns varchar(8000)
    as
    begin
        declare @ret varchar(8000)
        set @ret = ''
        select @ret = @ret+','+人员 from 表 where 部门 = @department
        set @ret = stuff(@ret,1,1,'')
        return @ret 
    end
    go
    --执行
    select 部门,人员=dbo.f_str(部门) from 表 group by 部门 order by 部门
    go--输出结果
    /*
    部门  人员
    ----  --------------
    1     张三,李四,王五
    2     赵六,邓七,刘八
    */
    --删除测试数据
    drop function f_str
    drop table 表
    go
      

  2.   

    create table tb(编号 varchar(20),姓名 nvarchar(50))
    insert into tb(编号,姓名)
    select '01','张' union all
    select '01','王' union all
    select '02','李'
    goCREATE FUNCTION dbo.get (@b varchar(20))  
    RETURNS nvarchar(500)
    AS  
    BEGIN 
    declare @s nvarchar(500)
    set @s = ''
    select @s = @s + 姓名 + ',' from tb where 编号 = @b
    return left(@s,len(@s) -1)
    END
    go
    select 编号,dbo.get(编号) from tb group by 编号
    go
    drop table tb
    drop function dbo.get
      

  3.   

    用SQL 2005吧。直接有行列转换的表函数。哈哈哈
      

  4.   

    我也给一个我做过的例子:
    declare @c1 varchar(100),
    @c2 varchar(100),
    @s1 varchar(20),
    @s2 varchar(20)
    declare ewaytempcolor insensitive cursor for 
    select styleid,c_name from ewaycolor where c_name not like '%、%' order by styleid
    open ewaytempcolor
    fetch next from ewaytempcolor into @s1,@c1
    while @@fetch_status=0
    begin
    fetch next from ewaytempcolor into @s2,@c2
    if @s1=@s2
    begin
    set @c1=@c1+'、'+@c2
    end
    else
    begin
    update ewaycolor set c_name=@c1 where styleid=@s1
    set @c1=@c2
    set @s1=@s2
    end
    end
    close ewaytempcolor
    deallocate ewaytempcolor