表结构(ID是唯一主键)
CREATE TABLE [dbo].[TestTable](
[ID] [int] NOT NULL,
[A] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
[B] [int] NOT NULL,
) ON [PRIMARY]记录:
ID       A        B
9 A 1
23 A 3
90 A 99
43 B 1
5 B 2
45 B 3
56 C 7
76 F 2
89 F 3排序查询:
select * from Table_4 order by A ASC,B DESC
ID       A        B
90 A 99
23 A 3
9 A 1
45 B 3
5 B 2
43 B 1
56 C 7
89 F 3
76 F 2
已知ID=9 根据order by A ASC,B DESC 排序求上一条与下一条ID值
按理上一条ID应为 23 下一条ID应为 45
select top 1 * from Table_4 where ID<>9 AND A<='A' AND B>=1  order by A DESC,B ASC
虽然求出了上一条ID=23,但不肯定是否对而下一条记录要怎么求出ID=45呢?

解决方案 »

  1.   

    CREATE TABLE [dbo].[TestTable](
    [ID] [int] NOT NULL,
    [A] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
    [B] [int] NOT NULL,
    ) ON [PRIMARY]
    insert into TestTable select 9,'A',1
    insert into TestTable select 23,'A',3
    insert into TestTable select 90,'A',99
    insert into TestTable select 43,'B',1
    insert into TestTable select 5,'B',2
    insert into TestTable select 45,'B',3
    insert into TestTable select 56,'C',7
    insert into TestTable select 76,'F',2
    insert into TestTable select 89,'F',3
    go
    ;with c1 as(
    select *,row_number()over(order by A asc,B desc)rn from TestTable
    ),c2 as(
    select rn from c1 where id=9
    )select id from c1 a where exists(select 1 from c2 where rn between a.rn-1 and a.rn+1) --order by rn
    /*
    id
    -----------
    23
    9
    45(3 行受影响)*/
    go
    drop table testtable
      

  2.   

    or:
    CREATE TABLE [dbo].[TestTable](
    [ID] [int] NOT NULL,
    [A] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
    [B] [int] NOT NULL,
    ) ON [PRIMARY]
    insert into TestTable select 9,'A',1
    insert into TestTable select 23,'A',3
    insert into TestTable select 90,'A',99
    insert into TestTable select 43,'B',1
    insert into TestTable select 5,'B',2
    insert into TestTable select 45,'B',3
    insert into TestTable select 56,'C',7
    insert into TestTable select 76,'F',2
    insert into TestTable select 89,'F',3
    go
    ;with c1 as(
    select *,row_number()over(order by A asc,B desc)rn from TestTable
    )select top 3 id from c1 order by round(abs(rn-(select rn from c1 where id=9))/2,1),rn
    /*
    id
    -----------
    23
    9
    45(3 行受影响)*/
    go
    drop table testtable