我需要使用定义的步长值在两个列值之间获取多个行。例如,如果表格如下所示:
Id Name
-----------------------
1 Maria Anders
2 Christina Berglund
3 Francisco Chang
4 Roland Mendel
5 Diego Roel
6 Eduardo Saavedra
7 Helen Bennett
8 Philip Cramer
和First = 3, Last = 7, Step = 2
,查询应返回:
Id Name
-----------------------
3 Francisco Chang
5 Diego Roel
7 Helen Bennett
我在考虑使用模数来指定应该返回哪些列,例如:
SELECT *
FROM Table
WHERE (i-3) % 2 = 0
这种方法将导致SQL Server迭代整个表并计算每个项的表达式。由于我希望步长值相对较大,我想知道是否有一种策略可以避免这种情况(可能使用索引来“跳过”项目)。
有更好的(读取:更快)方式吗? (我正在使用MS SQL Server 2008 R2)
答案 0 :(得分:4)
select * from table
where (id >= @start)
AND (id<=@end)
AND ((id-@start)%@step) = 0
测试用例:
declare @start int =3,
@end int = 7,
@step int =2
;with t(id)
as
(
select 1
union select 2
union select 3
union select 4
union select 5
union select 6
union select 7
union select 8
)
select * from t
where (id >= @start) AND (id<=@end) and ((id-@start)%@step) = 0
输出:
3
5
7
答案 1 :(得分:4)
DECLARE @start int = 3, @step int = 2, @stop int = 7;
;WITH cte AS
(
SELECT @start AS ID
UNION ALL
SELECT ID + @step FROM cte WHERE ID + @step <= @stop
)
SELECT *
FROM cte JOIN MyTable M ON cte.ID = MyTable.ID