sql查询前后两位

 

SQL排名的问题,A这个人在数据库里排第十,怎么查询一个他前面两位,后面两位,包括自己的五条数据,各位有啥高招?

sql查询前后两位
DECLARE @table TABLE
    (
      id INT PRIMARY KEY
             IDENTITY(1, 1) ,
      NAME VARCHAR(20)
    )
INSERT  INTO @table( NAME )VALUES  ( AA )
INSERT  INTO @table( NAME )VALUES  ( BB )
INSERT  INTO @table( NAME )VALUES  ( CC )
INSERT  INTO @table( NAME )VALUES  ( DD )
INSERT  INTO @table( NAME )VALUES  ( EE )
INSERT  INTO @table( NAME )VALUES  ( FF )
INSERT  INTO @table( NAME )VALUES  ( GG )
INSERT  INTO @table( NAME )VALUES  ( HH )
INSERT  INTO @table( NAME )VALUES  ( II )
INSERT  INTO @table( NAME )VALUES  ( JJ )
sql查询前后两位


方法: 1 .添加一个列,排序,记录中间需要的 mun 数,之后利用 between and 查询

sql查询前后两位
DECLARE @min INT ,
@max INT

SELECT  @min = v.mun - 2 ,
        @max = v.mun + 2
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY id ASC ) AS mun ,id,NAME
          FROM      @table
        ) v
WHERE   v.NAME = ee

SELECT  w.id ,
        w.NAME
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY id ASC ) AS mun ,id,name
          FROM      @table
        ) w
WHERE   w.mun BETWEEN @min AND @max
sql查询前后两位

 

方法2. 利用链表查询,将一个分成两个集合,利用on 做条件 ON t1.mun BETWEEN t2.mun - 2 AND t2.mun + 2

sql查询前后两位
SELECT  t1.id ,
        t1.NAME
FROM    ( SELECT ROW_NUMBER() OVER ( ORDER BY id ASC ) AS mun ,id ,NAME
          FROM      @table
        ) T1
        RIGHT JOIN 
        ( SELECT ROW_NUMBER() OVER ( ORDER BY id ASC ) AS mun ,id ,NAME
                     FROM   @table
        ) T2 ON t1.mun BETWEEN t2.mun - 2 AND t2.mun + 2
WHERE   T2.NAME = EE
sql查询前后两位

 

方法3. 利用EXISTS

例子

sql查询前后两位
SELECT  *
FROM    @table T1
WHERE   EXISTS 
        ( SELECT *
                 FROM   @table T2
                 WHERE  T2.NAME = EE
                        AND T1.id BETWEEN T2.id - 2 AND T2.id + 2 )
sql查询前后两位

完善

sql查询前后两位
SELECT  T1.id ,T1.name
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY id ASC ) AS mun ,id ,NAME
          FROM      @table
        ) T1
WHERE   EXISTS 
        ( SELECT mun ,id ,NAME
                 FROM   ( SELECT    ROW_NUMBER() OVER ( ORDER BY id ASC ) AS mun ,id ,NAME
                          FROM      @table
                        ) T2
                 WHERE  T2.NAME = EE
                        AND T1.mun BETWEEN T2.mun - 2 AND T2.mun + 2 
        )
sql查询前后两位

 

张姿势了~_~!

sql查询前后两位,布布扣,bubuko.com

sql查询前后两位

上一篇:PowerDesigner生成SQL语句时不使用Domain


下一篇:01.Android崩溃Crash封装库