SQL日期、期间比较
我对某些时期的比较逻辑有一些问题。我的数据库中有一个表,如下所示:
Id | startDate | amount of weeks |
-----------------------------------
A1 | 2010-01-04 | 3
B3 | 2010-01-11 | 2
所有开始日期都在一周的同一天(星期一)开始。
现在我需要编写一个 SQL 查询,其中有 2 个参数(开始日期和新“周期”的周数),并且需要检查并返回 startDate 相同的所有行。但实际上位于新“句点”范围内的所有行也应该返回。
一些例子来澄清这一点:
- When I give the following parameters (2010-01-04, 1) I would need to have row 1 with id A1 returned
- (2010-01-11, 1) ---> return A1,B3
- (2009-12-28, 1) ---> return nothing
- (2009-12-28, 2) ---> return A1
- (2010-01-18, 1) ---> return A1,B3
现在我知道如何使用参数等 - 所以我基本上需要一些关于构建 SQL 查询的逻辑的帮助。
SELECT Id FROM table WHERE startDate={0} or startDate={1} .....
我正在使用 SQL Server(但我认为非方言 SQL 也可以做到这一点)。
I'm having some problem with logic of the comparison of some periods. I have a table in my database that looks like this:
Id | startDate | amount of weeks |
-----------------------------------
A1 | 2010-01-04 | 3
B3 | 2010-01-11 | 2
All the startDates start on the same day of the week (Monday).
Now I need to write a SQL query where I have 2 parameters (a start date, and the amount of weeks of a new 'period') and I need to check and return all the rows for which the startDate is the same. But all the rows which are actually within the range of the new 'period' should be returned, as well.
Some examples to clarify this:
- When I give the following parameters (2010-01-04, 1) I would need to have row 1 with id A1 returned
- (2010-01-11, 1) ---> return A1,B3
- (2009-12-28, 1) ---> return nothing
- (2009-12-28, 2) ---> return A1
- (2010-01-18, 1) ---> return A1,B3
Now I know how to work with parameters, etc. - so I basically would need a little help on the logic to build up the SQL query.
SELECT Id FROM table WHERE startDate={0} or startDate={1} .....
I'm working with SQL Server (but I think non-dialect SQL can do the trick, as well).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您的问题是通用的,其他人可能会提出略有不同的要求:
Surely SQL Server has an interval-type?这将使提供的查询更简单,并且您可以处理任意间隔,而不仅仅是几周。我对 SQL Server 没有经验——它如何处理这些 int-to-interval-casts wrt。到索引?如果需要功能索引,您不妨存储三个日期。这还可以让您处理未来可能需要的不同前后间隔的要求。
Since your question is generic, and others can end up here with slightly different requirements:
Surely SQL Server has an interval-type? That would make the provided queries simpler, and you could handle arbitrary intervals, not just weeks. I'm not experienced with SQL Server --- how will it fare with those int-to-interval-casts wrt. to indexes? If a functional index is required, you might as well store a triple of dates. That'll also let you handle a possible future requirement of different before- and after-intervals.
这会起作用:
编辑:我误解了你的问题。这应该是一个可行的解决方案:
This will work:
EDIT: I misunderstood your question. this should be a working solution:
试试这个
try this