Sorry, after reading Dan's response, I realize I misunderstood the question.
A slightly different approach (which also accounts for the case where start
and end time are the same, and lastupdated falls on that instant):
CREATE TABLE #foo
(
i INT,
LastUpdated DATETIME,
StartTime SMALLDATETIME,
EndTime SMALLDATETIME
);
SET NOCOUNT ON;
INSERT #foo SELECT 1,'2007-05-29 01:04:32', '05:00 PM', '02:00 AM'; --
should match
INSERT #foo SELECT 2,'2007-05-29 12:04:32', '05:00 PM', '02:00 AM';
INSERT #foo SELECT 3,'2007-05-29 16:04:32', '05:00 PM', '02:00 AM';
INSERT #foo SELECT 4,'2007-05-29 19:04:32', '05:00 PM', '02:00 AM'; --
should match
INSERT #foo SELECT 5,'2007-05-29 16:04:32', '05:00 PM', '11:00 PM';
INSERT #foo SELECT 6,'2007-05-29 16:04:32', '03:00 PM', '07:00 PM'; --
should match
SELECT i,LastUpdated
FROM (
SELECT i,LastUpdated,
delta = DATEDIFF(MINUTE,0,DATEADD(DAY,-DATEDIFF(DAY,0,LastUpdated),
LastUpdated)),
s = DATEDIFF(MINUTE,0,StartTime),
e = DATEDIFF(MINUTE,0,EndTime),
r = ABS(DATEDIFF(MINUTE,StartTime,EndTime))
FROM #foo
) x
WHERE (delta BETWEEN s AND s+r)
OR delta = CASE WHEN s = e THEN delta ELSE -1 END
OR delta <= CASE WHEN e < s THEN e ELSE -1 END;
DROP TABLE #foo;