create table test_a 
(id int)create table test_b
(id int)insert test_a
select 1 union all
select 2 union all
select 3 union all
select 5 union all
select 7insert test_b
select 1 union all
select 2 union all
select 3 union all
select 5 union all
select 6 select id as id_1,id_2=(select min(id) from test_b a where a.id>b.id) from test_a b
drop table test_a,test_b
id_1        id_2        
----------- ----------- 
1           2
2           3
3           5
5           6
7           NULL(所影响的行数为 5 行)

解决方案 »

  1.   

    declare @t table (id int)declare @d table (id int)insert into @t select 1
    union all select 2
    union all select 3
    union all select 5
    union all select 7insert into @d select  1
    union all select 2
    union all select 3
    union all select 5
    union all select 6select t.id as id_1,(select min(d.id) from @d d where d.id>t.id) as id_2 from @t t/*id_1        id_2        
    ----------- ----------- 
    1           2
    2           3
    3           5
    5           6
    7           NULL
    */
      

  2.   

    不好意思,问题的结果写错了,
    得出的结果应该是:  
    id_1      id_2  
     1          2  
     2          3  
     3          5  
     5          6  
     7          Null
      

  3.   

    select id as [id_1],[id_2]=(select min(id) from test_b a where a.id>b.id) from test_a b
      

  4.   


    create table a(id int)create table b (id int)insert into a select 1
    union all select 2
    union all select 3
    union all select 5
    union all select 7insert into b select  1
    union all select 2
    union all select 3
    union all select 5
    union all select 6select a.id as id1 ,min(b.id) as id2  from a left join b on b.id>a.id
    group by a.idid1         id2         
    ----------- ----------- 
    1           2
    2           3
    3           5
    5           6
    7           NULL(所影响的行数为 5 行)
      

  5.   


    declare @t_a table(id int)
    insert @t_a
    select   1 union all
    select  2 union all
    select  3 union all
    select  5 union all
    select  7declare @t_b table(id int)
    insert @t_b
    --test_b的结构如下:  
    select  1 union all
    select  2 union all
    select  3 union all
    select  5 union all
    select  6select id_1=a.id,
           id_2=(select min(id) from @t_b b where b.id>a.id)
    from @t_a a
    /*
    id_1        id_2        
    ----------- ----------- 
    1           2
    2           3
    3           5
    5           6
    7           NULL
    */
      

  6.   

    如果在Test_b中加多一个字段,比如说
      id    count
      1      1000
      2      2000
      3      3000
      5      4000
      6      5000
    然后要显示结果是
    id1         id2         count
    ----------- ----------- 
    1           2           2000
    2           3           3000
    3           5           5000
    5           6           6000
    7           NULL        Null
    又应该怎么做呢?