我有一个包含周数的列和一个包含年份数的列。我想在数据库中搜索一段时间间隔,例如:
如果我想在今年的一周和明年的一周之间进行搜索,我应该使用哪种查询?
如果年份相同,那将很容易,我的查询将如下所示:
Select *
From mytable
Where (Finish_Week BETWEEN @Finish_Week1 AND @Finish_Week2)
AND (Finish_Year = @Finish_Year)
答案 0 :(得分:2)
简单回答:
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是第二年。
简短说明:
答案 1 :(得分:0)
此解决方案适用于任何年龄段,与其他答案不同,它们不必相隔一年。它将年份+周规范化为可以直接比较的线性格式。
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
答案 2 :(得分:0)
我认为如果你在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
)
如果您没有索引,可以考虑将周和年转换为日期,然后比较日期。