数据:
aaa   bbbb    amount
111   222     333
222   222     444
111   333     555 
111   222     777 结果:
aaa   bbbb    amount
111   222     333,777
222   222     444
111   333     555--------------------------
amount 中,多个结果用 , 隔开。

解决方案 »

  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 TEST
    (aaa Int,
     bbbb Int,
     amount Int)
    Insert TEST Select 111,   222,     333
    Union All Select 222,   222,     444
    Union All Select 111,   333,     555 
    Union All Select 111,   222,     777 
    GO
    Create Function Getamount(@aaa Int, @bbbb Int)
    Returns Varchar(8000)
    As
    Begin
    Declare @S Varchar(8000)
    Select @S = ''
    Select @S = @S + ',' + Rtrim(amount) From TEST Where aaa = @aaa And bbbb = @bbbb
    Select @S = Stuff(@S , 1, 1 ,'')
    Return @S
    End
    GO
    Select
    aaa,
    bbbb,
    dbo.Getamount(aaa, bbbb) As amount
    From 
    TEST
    Group By aaa, bbbb
    GO
    Drop Table TEST
    Drop Function Getamount
    --Result
    /*
    aaa bbbb amount
    111 222 333,777
    111 333 555
    222 222 444
    */
      

  3.   

    create table ta(aaa int, bbbb int,   amount int)
    insert ta
    select 111,   222,     333 union all
    select 222,   222,     444 union all
    select 111,   333,     555 union all
    select 111,   222,     777create function test_f(@a int,@b int)
    returns varchar(1000)
    as
    begin 
        declare @sql varchar(1000)
        select @sql=isnull(@sql+',','')+rtrim(amount) 
        from ta where aaa=@a and bbbb=@b
        return @sql
    endselect distinct aaa,bbbb,dbo.test_f(aaa,bbbb)from ta
    aaa         bbbb        
    ----------- ----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    111         222         333,777
    111         333         555
    222         222         444(3 行受影响)