您可以简单地扩大范围,但这可能会带回与您预期不同的记录。
SELECT RECORD, EVENT, TIME
FROM SO_RecordEvent AS R
WHERE TIme BETWEEN '6/26/2012 9:55AM' AND '6/26/2012 11:06AM'
这将返回范围内开始或结束时间的任何记录的所有记录,包括超出范围的关联记录(换句话说,在范围内只有一个时间的记录 - 但开始于或结束于之后 - 它仍会显示它之外的开始或结束时间)并允许您缩短范围。
;WITH X AS
(
SELECT RECORD,EVENT,TIME FROM SO_RecordEvent
)
SELECT R.RECORD,R.EVENT,R.TIME
FROM SO_RecordEvent AS R
INNER JOIN X ON R.Record = X.Record
WHERE X.TIme BETWEEN '6/26/2012 10:05AM' AND '6/26/2012 11:05AM'
GROUP BY R.RECORD,R.EVENT,R.TIME
但我认为您可能真的想要这样的东西,它确实为您提供了在那段时间开始的一切,即使它开始和结束超出范围,就像您的记录 2 示例一样。
编辑
改变逻辑 - 决定以这种方式思考问题,而不是解决问题 - 在开始和结束内开始的任何事情,在开始和结束内结束的任何事情,以及之前开始和之后结束的任何事情。我认为这涵盖了在此期间运行的任何内容(开始之前结束,开始和结束,开始和结束之后,开始之前和之后结束)
SELECT X.RECORD,X.TIME AS STARTTIME,Y.TIME AS ENDTIME
FROM SO_RecordEvent AS X
INNER JOIN SO_RecordEvent Y ON Y.Record = X.Record AND Y.EVENT = 'END'
WHERE X.EVENT = 'START'
AND
((X.TIME >= '6/26/2012 10:00AM' AND X.TIME <= '6/26/2012 11:00AM')
OR (Y.TIME >= '6/26/2012 10:00AM' AND Y.TIME <= '6/26/2012 11:00AM')
OR (X.TIME <= '6/26/2012 10:00AM' AND Y.TIME >= '6/26/2012 11:00AM'))
要玩的变量:
DECLARE @START datetime, @END datetime
SET @START = '6/26/2012 10:00AM'
SET @END = '6/26/2012 11:00AM'
SELECT X.RECORD,X.TIME AS STARTTIME,Y.TIME AS ENDTIME
FROM SO_RecordEvent AS X
INNER JOIN SO_RecordEvent Y ON Y.Record = X.Record AND Y.EVENT = 'END'
WHERE X.EVENT = 'START'
AND
((X.TIME >= @START AND X.TIME <= @END)
OR (Y.TIME >= @START AND Y.TIME <= @END)
OR (X.TIME <= @START AND Y.TIME >= @END))