选择记录任一侧的行

时间:2014-10-25 12:06:36

标签: sql sql-server tsql

我想从我拥有的图像表中选择记录两侧的4行。

到目前为止,我有以下内容: -

with myresults as(
    select mykey, imageThumb,ROW_NUMBER() OVER (ORDER BY mykey)AS Row from images where userid = @userID
)

select * from myresults where 

row < ((select row from myresults where mykey=@imageID)+5)
and
row > ((select row from myresults where mykey=@imageID)-5)

这确实可以,但我想知道是否有更好/更简单的方法

由于

2 个答案:

答案 0 :(得分:2)

您走在正确的轨道上,但您需要先执行row_number(),然后再执行where。以下是使用cross join的一种方法:

with myresults as(
    select mykey, imageThumb, ROW_NUMBER() OVER (ORDER BY mykey) as Row
    from images
)  
select m.*
from myresults m cross join
     (select * from myresults where where userid = @userID) u
where m.row < u.row + 5 and m.row > u.r - 5;

答案 1 :(得分:1)

使用自联接你可以轻松实现目标。试试这个

WITH myresults
     AS (SELECT Row_number()
                  OVER (
                    ORDER BY mykey)AS Rn,
                mykey,
                imageThumb
         FROM   images where userid = @userID)
SELECT *
FROM   myresults a
       JOIN myresults b
         ON a.rn BETWEEN b.Rn - 5 AND b.rn + 5
WHERE  a.mykey = @imageID 

示例

CREATE TABLE #images
  (
     mykey      INT,
     imageThumb VARCHAR(50)
  );

WITH cte
     AS (SELECT 1       AS id,
                Newid() AS d
         UNION ALL
         SELECT id + 1,
                Newid() d
         FROM   cte
         WHERE  id < 10)
INSERT INTO #images
SELECT *
FROM   cte;

WITH myresults
     AS (SELECT Row_number()
                  OVER (
                    ORDER BY mykey)AS Rn,
                mykey,
                imageThumb
         FROM   #images)
SELECT *
FROM   myresults a
       JOIN myresults b
         ON a.rn BETWEEN b.Rn - 3 AND b.rn + 3
WHERE  a.mykey = 4