sql查詢前后兩位


 

SQL排名的問題,A這個人在數據庫里排第十,怎么查詢一個他前面兩位,后面兩位,包括自己的五條數據,各位有啥高招?

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' )


方法: 1 .添加一個列,排序,記錄中間需要的 mun 數,之后利用 between and 查詢

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

 

方法2. 利用鏈表查詢,將一個分成兩個集合,利用on 做條件 ON t1.mun BETWEEN t2.mun - 2 AND t2.mun + 2

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'

 

方法3. 利用EXISTS

例子

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 )

完善

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 
        )

 

張姿勢了~_~!


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com