如何将表中某一字段所有记录用一个SQL返回一行?举个例子,
table_1(fcol) 有三行分别为
1  a
2  b
3  c
怎么用一句SQL返回 a,b,c,?以前用过但现在要用又怎么想也想不出来,期望各位兄台给予解答,谢谢!!!

解决方案 »

  1.   


    declare @a table(a varchar(10))
    insert @a select 'a'
    union all
    select 'b'
    union all
    select 'c'declare @s varchar(100)
    set @s=''
    select @s=@s+','+a from @a
    select right(@s,len(@s)-1)
      

  2.   

    --LZ是要问字符串拼接吧
    --给个例子
    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
      

  3.   

    非常感谢,恍然大悟,原来是记错了,我老以为一个SQL可以实现,唉,钴死胡同了.