gpt4 book ai didi

SQL选择步骤

转载 作者:行者123 更新时间:2023-12-02 07:07:23 25 4
gpt4 key购买 nike

我需要使用定义的步长值在两列值之间获取多行。例如,如果表如下所示:

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)

最佳答案

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

关于SQL选择步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9632260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com