我有相当复杂的连接查询,我想从中选择具有特定 id 的结果周围的几行。
查询当前看起来像这样:
WITH results AS
(
SELECT t1.id, t1.position, t1.points, t2.name
ROW_NUMBER() OVER(ORDER BY t1.position ASC, t1.points DESC) AS rn
FROM Table1 t1
JOIN Table2 t2 ON t1.id = t2.Table1id
/* Several more joins here, some of which limit the result set */
)
SELECT * FROM results
WHERE rn < ( SELECT rn+3 FROM results WHERE id = @someid )
AND rn > ( SELECT rn-3 FROM results WHERE id = @someid )
有没有更好的方法来解决这个问题?最重要的是,我担心这些对可能巨大的 CTE 的多次调用的性能。
该查询在SQL 2008服务器上运行。