0

我有以下查询,它将检索作为参数提供的开始日期和结束日期之间的事件:

SELECT * FROM events
WHERE (startDate BETWEEN CAST(@start AS DATETIME) AND CAST(@end AS DATETIME)
OR endDate BETWEEN CAST(@start AS DATETIME) AND CAST(@end AS DATETIME))

这适用于检索与开始时间和结束时间重叠的事件,但不会获得在这些时间之间完全封装的事件。一张图片可能会更清楚:

Event A |------------------------------------------------------------------| Event B ----------------------|------------|-------------------------------

Where | represents a start or end date

在我的图片中,使用事件 B 的开始和结束时间查询,它不会检索事件 A。

如何更改查询以显示所有重叠和封装的事件?

4

2 回答 2

2
SELECT * FROM events
WHERE (startDate BETWEEN CAST(@start AS DATETIME) AND CAST(@end AS DATETIME)
OR endDate BETWEEN CAST(@start AS DATETIME) AND CAST(@end AS DATETIME))
OR (endDate >= CAST(@end AS DATETIME)) AND startDate <= CAST(@end AS DATETIME))

最后OR一行将添加 start 小于 end 参数并且 end 大于该参数的所有行。这样所有与@end 重叠的行都将被匹配。你也可以试试:

SELECT * FROM events
WHERE 
 (startDate <= CAST(@start AS DATETIME)) AND endDate >= CAST(@start AS DATETIME))
OR (endDate >= CAST(@end AS DATETIME)) AND startDate <= CAST(@end AS DATETIME))

这应该符合你想要的一切。它匹配超过start或 的每条记录end。如果您还想匹配包含在其中的所有内容startend但不与其中任何一个重叠,则可能必须将其与 between 结合使用。

于 2013-05-20T19:15:07.147 回答
1

你所要做的

SELECT * FROM events
WHERE (startDate <= CAST(@end AS DATETIME) AND endDate >= CAST(@start AS DATETIME)
于 2013-05-20T19:13:53.527 回答