Path_Name  Item_ID    Item_Name            
---------- ---------- -------------------- 
A          1          裁                  
A          2          剪                  
A          3          冲压                
B          1          折弯                
B          2          激光切割            
B          3          冲孔                
B          4          冲压   
这是原表结构。想等到如下结果: 
path_name    item_name
---------    -----------
A             裁+剪+冲压 
B             折弯+激光切割+冲孔+冲压 Item项数量不确定的。在线等请高手赐教!

解决方案 »

  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 T(Path_Name char(1),  Item_ID int ,    Item_Name nvarchar(10))
    insert T select 'A',          1,          '裁'                  
    union all select 'A',         2,          '剪'                  
    union all select 'A',          3,          '冲压'                
    union all select 'B',          1,          '折弯'                
    union all select 'B',          2,          '激光切割'            
    union all select 'B',          3,          '冲孔'                
    union all select 'B',          4,          '冲压'   
    create function fun(@Path_Name char(1))
    returns nvarchar(4000)
    as 
    begin
    declare @re nvarchar(4000)
    set @re=''
    select @re=@re+Item_Name+'+' from T where Path_Name=@Path_Name order by Item_ID

    select @re=LEFT(@re, len(@re)-1)
    return @re
    endselect Path_Name, dbo.fun(Path_Name) as item_name from T group by Path_Name
    --result
    Path_Name item_name        
    --------- -------------------------------------------
    A         裁+剪+冲压
    B         折弯+激光切割+冲孔+冲压(2 row(s) affected)
      

  3.   

    --刪除環境
    drop table T
    drop function fun
      

  4.   

    结贴.谢谢:marco08(天道酬勤)
    aw511(点点星灯