我数据有一个字段为 MediaID    MediaID
      12
      23
      34
      45
      56
      78
      87
      97我现在想以 MediaID 为56 的数据为 核心,分别取其 前 2条,和 后2条数据如何完成?
望高手赐教

解决方案 »

  1.   

    if object_id('tempdb.dbo.#T1') is not null drop table #T1
    go
    create table #T1 ([MediaID] int)
    insert into #T1
    select 12 union all
    select 23 union all
    select 34 union all
    select 45 union all
    select 56 union all
    select 78 union all
    select 87 union all
    select 97
    ;with tt
    as(
    select [cnt]=row_number()over(order by [MediaID]),
           [MediaID]
    from #T1
    )
    select top 4 * from tt
    where cnt!=(select top 1 cnt from tt where [MediaID]=56)
    order by abs((select top 1 cnt from tt where [MediaID]=56)-cnt)
    /*
    cnt                  MediaID
    -------------------- -----------
    6                    78
    4                    45
    3                    34
    7                    87
    */
      

  2.   

    if object_id('tempdb.dbo.#T1') is not null drop table #T1
    go
    create table #T1 ([MediaID] int)
    insert into #T1
    select 12 union all
    select 23 union all
    select 34 union all
    select 45 union all
    select 56 union all
    select 78 union all
    select 87 union all
    select 97
    select top 100 percent * from
    (
    select top 2 *  from #T1 where [MediaID]<56 order by [MediaID] desc
    )a
    union all
    select top 100 percent * from
    (
    select top 2 *  from #T1 where [MediaID]>56 order by [MediaID] desc
    )b
    /*
    MediaID
    -----------
    45
    34
    97
    87(4 row(s) affected)
    */
      

  3.   

    if object_id('tempdb.dbo.#T1') is not null drop table #T1
    go
    create table #T1 ([MediaID] int)
    insert into #T1
    select 12 union all
    select 23 union all
    select 34 union all
    select 45 union all
    select 56 union all
    select 78 union all
    select 87 union all
    select 97
    select top 4 * from #T1 where [MediaID]<>56
     order by abs([MediaID]-56)
     
     /*
     MediaID
    -----------
    45
    78
    34
    87
      

  4.   

    最终解决方法  查2次,然后把 2次 的结果   union all  起来谢谢大家
      

  5.   

    top  2排序加union all
      

  6.   


    create table t1
    (
    id int
    )
    insert into t1
    select 12 union all
    select 23 union all
    select 34 union all
    select 45 union all
    select 56 union all
    select 78 union all
    select 87 union all
    select 97
    select * from t1;with aaa as
    (
    select ROW_NUMBER() over(order by id) as row,* from t1
    )
    select * from aaa where ABS(row-(select row from aaa where id=56))<=2