首先过滤,然后选择页面

时间:2010-12-31 12:03:51

标签: sql-server

如何首先根据params过滤结果然后应用于何处? 有点像

With Results as
(
    Select colName,Title, Row_Number(Over...) as row from a table where colName=5
)
Select * from Results 
where 
row between @first and @last

但它不起作用。我需要将我的colName = 5从where子句移动到外部,然后我得到错误的数据,因为它首先获得@first n @last之间的行,然后搜索colName = 5。 我也想要结果数。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您的ROW_NUMBER语法不正确。它应该是这样的:

With Results as
(
    SELECT colName, Title, ROW_NUMBER() OVER (ORDER BY ...) AS RN
    FROM your_table
    WHERE colName = 5
)
SELECT * FROM Results 
WHERE rn BETWEEN @first AND @last
ORDER BY rn

有关详细信息,请参阅documentation

答案 1 :(得分:1)

您可以使用COUNT(*) OVER()来计算未经过滤的结果

WITH cte as
(
select *, 
ROW_NUMBER() over (order by name desc) AS RN, 
count(*) over() AS [Count]
from master..spt_values
)
SELECT name, number,[Count] 
FROM cte
WHERE RN BETWEEN 20 AND 24

返回

name                                number      Count
----------------------------------- ----------- -----------
VIEW                                8278        2506
VIEW                                8278        2506
view                                2           2506
varchar                             3           2506
varbinary                           1           2506

但这有性能影响。您可能只想预先计算COUNT并将其缓存到某个位置,而不是为每个页面请求重新计算它。

答案 2 :(得分:0)

我使用的方法与Martin Smiths(目前选择的答案)非常相似,至少在我做过的测试中,它提供了更好的性能结果。

; WITH cte as
(
select *, 
ROW_NUMBER() over (order by name desc) AS RN
from master..spt_values
)
SELECT name, number, (SELECT COUNT(*) FROM cte) AS [Count]
FROM cte
WHERE RN BETWEEN 20 AND 24

并排运行此查询和查询并比较执行计划。