首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sql -在日期时间开始、停止和停止之后选择记录

sql -在日期时间开始、停止和停止之后选择记录
EN

Stack Overflow用户
提问于 2014-07-28 09:21:37
回答 2查看 325关注 0票数 0

我有一张这样的桌子:

代码语言:javascript
复制
id timestart            timestop 
1  2014-5-5 23:15:00    2014-5-5 23:17:00
2  2014-5-5 23:30:00    2014-5-5 23:45:00
3  2014-5-5 23:50:00    2014-5-5 23:55:00
4  2014-5-5 23:57:00    2014-5-6 00:05:00

我有select语句,它在timestart和timestop之间返回记录:

代码语言:javascript
复制
select *
from table
where ( timestart >= @start and timestop <= @stop)

如果@start = '2014-5-5 23:00:00‘和@stop =’2014-5 23:59:00',则选择将返回前三行。我应该如何重写select语句以检索带有id=4的行(在timestart之后有@start,在timestop之后有@stop )?

通过这个声明,我得到了我想要的,但我不确定这是最好的方法:

代码语言:javascript
复制
... where 
    (timestart  >= @start and timestart <= @stop) and (timestop <= @stop or timestop >= @stop) 
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-07-28 09:27:16

从第二个查询中可以很容易地推断出

代码语言:javascript
复制
where (timestart >= @start and timestart <= @stop) 

甚至是

代码语言:javascript
复制
where (timestart BETWEEN @start and @stop) 

这是因为你陈述的第二部分

代码语言:javascript
复制
where (timestart >= @start and timestart <= @stop) 
and (timestop <= @stop or timestop >= @stop) <---this will be true for all timestop entries
票数 0
EN

Stack Overflow用户

发布于 2014-07-28 09:35:33

试试这个:

代码语言:javascript
复制
where timestart BETWEEN ISNULL(@start,timestart) and ISNULL(@stop,timestart)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24992084

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档