id,name,bm
1    a  01
1    a  02
2   b  01
3   c   01
如何写sql语句取出这样的记录集合,即把id,name 相同的bm放到同一行?
id,name,bm
1   a    01   02 
2   b    01
3   c    01

解决方案 »

  1.   

    --带符号合并行列转换--有表t,其数据如下:
      a b
      1 1
      1 2
      1 3
      2 1
      2 2
      3 1
    --如何转换成如下结果:
      a b
      1 1,2,3
      2 1,2
      3 1 create table tb
    (
      a int,
      b int
    )
    insert into tb(a,b) values(1,1)
    insert into tb(a,b) values(1,2)
    insert into tb(a,b) values(1,3)
    insert into tb(a,b) values(2,1)
    insert into tb(a,b) values(2,2)
    insert into tb(a,b) values(3,1)
    go--创建一个合并的函数
    create function f_hb(@a int)
    returns varchar(8000)
    as
    begin
      declare @str varchar(8000)
      set @str = ''
      select @str = @str + ',' + cast(b as varchar) from tb where a = @a 
      set @str = right(@str , len(@str) - 1)
      return(@str)
    End
    go--调用自定义函数得到结果:
    select distinct a ,dbo.f_hb(a) as b from tbdrop table tb--结果
    a           b     
    ----------- ------
    1           1,2,3
    2           1,2
    3           1(所影响的行数为 3 行)
      

  2.   

    id,name,bm
    1   a    01   02 
    2   b    01
    3   c    01
    --创建一个合并的函数
    create function f_hb(@id int,@name varchar)
    returns varchar(8000)
    as
    begin
      declare @str varchar(8000)
      set @str = ''
      select @str = @str + '''+ ''' + cast(bm as varchar) from tb where id = @id and name=@name
      set @str = right(@str , len(@str) - 1)
      return(@str)
    End
    go--调用自定义函数得到结果:
    select distinct id , name ,dbo.f_hb(id , name) as bm from tb
      

  3.   

    if object_id('pubs..tb') is not null
       drop table tb
    gocreate table tb
    (
    id int,
    name varchar(10),
    bm varchar(10)
    )
    insert into tb(id,name,bm) values(1,'a','01')
    insert into tb(id,name,bm) values(1,'a','02')
    insert into tb(id,name,bm) values(2,'b','01')
    insert into tb(id,name,bm) values(3,'c','01')
    go
    --创建一个合并的函数
    if object_id('pubs..f_hb') is not null
       drop table f_hb
    go
    create function f_hb(@id int,@name varchar)
    returns varchar(8000)
    as
    begin
      declare @str varchar(8000)
      set @str = ''
      select @str = @str + ' ' + cast(bm as varchar) from tb where id = @id and name=@name
      set @str = right(@str , len(@str) - 1)
      return(@str)
    End
    go--调用自定义函数得到结果:
    select distinct id , name ,dbo.f_hb(id , name) as bm from tbdrop table tb
    drop function f_hbid          name       bm    
    ----------- ---------- -----
    1           a          01 02
    2           b          01
    3           c          01(所影响的行数为 3 行)