我有一个带有周数的列和一个带有年份数的列。我想在数据库中搜索一个时间间隔,例如:
如果我想在今年的一周和明年的一周之间进行搜索,我应该使用什么查询?
如果年份相同,那将很容易,我的查询将如下所示:
Select *
From mytable
Where (Finish_Week BETWEEN @Finish_Week1 AND @Finish_Week2)
AND (Finish_Year = @Finish_Year)
我有一个带有周数的列和一个带有年份数的列。我想在数据库中搜索一个时间间隔,例如:
如果我想在今年的一周和明年的一周之间进行搜索,我应该使用什么查询?
如果年份相同,那将很容易,我的查询将如下所示:
Select *
From mytable
Where (Finish_Week BETWEEN @Finish_Week1 AND @Finish_Week2)
AND (Finish_Year = @Finish_Year)
简单的回答:
SELECT *
FROM MYTABLE
WHERE ( FINISH_WEEK >= @Finish_Week1
AND FINISH_YEAR = @Finish_Year - 1 )
OR ( FINISH_WEEK <= @Finish_Week2
AND FINISH_YEAR = @Finish_Year )
此解决方案假定 @Finish_Year 是第二年。
简短说明:
该解决方案适用于任何年份,它们不必像其他答案那样相隔一年。它将年+周规范化为可以直接比较的线性格式。
SELECT *
FROM mytable
WHERE Finish_Year*53+Finish_Week BETWEEN @Finish_Year1*53+@Finish_Week1 AND @Finish_Year2*53+@Finish_Week2
如果这太慢(因为表中有很多行)并且您在 Finish_Year 上有一个索引,请添加以下内容:
AND Finish_Year BETWEEN @Finish_Year1 AND @Finish_Year2
我认为如果您在 Finish_Week、Finish_Year 上有索引,那么最好的方法是写
select *
from mytable
where
(
Finish_Year = @Finish_Year and Finish_Week >= @Finish_Week1 or
Finish_Year = @Finish_Year + 1 and Finish_Week <= @Finish_Week2
)
如果您没有索引,您可以考虑将周和年转换为日期,然后比较日期。