表格如下id1 name num 
 1   章 1
 1   了 2
 2   可  1
 2   喔  2
 3   啊 1
 ..  ..  ..num只限于1,2 希望得到如下自定义函数select * from f()id name1 name2
1   章  了   
2   可  喔
3   啊  每
 

解决方案 »

  1.   

    用函数影响效率
    --> 测试数据: #tb
    if object_id('tempdb.dbo.#tb') is not null drop table #tb
    go 
    create table #tb (id1 int,name varchar(2),num int)
    insert into #tb
    select 1,'章',1 union all
    select 1,'了',2 union all
    select 2,'可',1 union all
    select 2,'喔',2 union all
    select 3,'啊',1select id1,
    name1=max(case when num=1 then name end), 
    name2=max(case when num=2 then name end)  
     from #tb
    group by id1
    id1         name1 name2
    ----------- ----- -----
    1           章     了
    2           可     喔
    3           啊     NULL
    警告: 聚合或其他 SET 操作消除了空值。(3 行受影响)
      

  2.   

    select a.id,a.name as name1,b.name as name2 from TB as a inner join TB as b on a.id=b.id
      

  3.   

    create table tb(id1 int,name varchar(2),num int)
    insert into tb
    select 1,'章',1 union all
    select 1,'了',2 union all
    select 2,'可',1 union all
    select 2,'喔',2 union all
    select 3,'啊',1 union all
    select 3,'每',2
    go
    select a.id1,a.name,b.name
    from tb a left join tb b on a.id1=b.id1
    where a.num=1 and b.num=2
    go
    drop table tb
    /*
    id1         name name
    ----------- ---- ----
    1           章    了
    2           可    喔
    3           啊    每(3 行受影响)*/
      

  4.   

    if object_id('tb') is not null 
    drop table tb
    go 
    create table tb (id1 int,name varchar(2),num int)
    insert into tb
    select 1,'章',1 union all
    select 1,'了',2 union all
    select 2,'可',1 union all
    select 2,'喔',2 union all
    select 3,'啊',1create function f()
    returns table
    as
    return
    (
      select id1,
        name1=max(case when num=1 then name else '' end), 
        name2=max(case when num=2 then name else '' end)  
     from tb
     group by id1
    )
    goselect * from f()
    /**
    id1         name1 name2
    ----------- ----- -----
    1           章     了
    2           可     喔
    3           啊     (3 行受影响)
    **/