表:tbl-n有以下数据
姓名    排号   座号
-------------------------------
老大    A      01 
老二    A      09
张三    C      02
李四    B      06
五牛    D      03
六哥    B      01
鬼脚七  A      05写一SQL语句,显示下列结果
排号   座号
---------------------
 A    01、09、05
 B    06、01
 C    02
 D    03

解决方案 »

  1.   

    函数
    if object_id('testfunc') is not null drop table testfunc
    go
    create function testfunc(@排号 varchar(20)) returns varchar(100)
    as
    begin
      declare @s varchar(100)
      set @s = ''
      select @s = @s + 座号 + ','
      from tbl-n where 排号 = @排号
      return(left(@s, len(@s) - 1))
    end
    go
    select distinct 排号,dbo.testfunc(排号) as 座号
    from tbl-ndrop function testfunction
      

  2.   

    if object_id('[tbl-n]') is not null drop table [tbl-n]
    select '老大' as 姓名, 'A' as 排号, '01' as 座号
    into [tbl-n]
    union select '老二', 'A', '09'
    union select '张三', 'C', '02'
    union select '李四', 'B', '06'
    union select '五牛', 'D', '03'
    union select '六哥', 'B', '01'
    union select '鬼脚七', 'A', '05'
    ------------------------------------------ 
    if object_id('testfunc') is not null drop function testfunc
    go
    create function testfunc(@排号 varchar(20)) returns varchar(100)
    as
    begin
      declare @s varchar(100)
      set @s = ''
      select @s = @s + 座号 + '、'
      from [tbl-n] where 排号 = @排号
      return(left(@s, len(@s) - 1))
    end
    go
    select distinct 排号,dbo.testfunc(排号) as 座号
    from [tbl-n]
    /*
    排号   座号
    A      05、01、09
    B      06、01
    C      02
    D      03
    */
    drop function testfunc
    ------------------------------------------
    drop table [tbl-n]