I feel like there exists a query that returns the data I'm looking for. I just can't seem to get my brain to tell me what it is
Perhaps I've been staring at it too long. Any help would be appreciated ![]()
Let's say you have a table called WINDOW that has a START date, an END date and a unique ID.
I want to select all the rows that are within 10 minutes of each other and at least one of the rows falls within a given datetime (which I pass in my query).
Here's a sample dataset:
ID, START, END
1, 9/21/09 00:00:00, 9/21/09 00:30:00
2, 9/21/09 00:38:00, 9/21/09 02:00:00
3, 9/21/09 02:05:00, 9/21/09 04:00:00
4, 9/21/09 04:15:00, 9/21/09 04:30:00
5, 9/21/09 04:35:00, 9/21/09 07:30:00
Rows 1 -> 2 -> 3 are a set because 2's START is only 8 minutes greater than 1's END and 3's START is only 5 greater than 2's END. Following that rule, 4 and 5 are a set as well.
Passing in the datetime 9/21/09 02:00:00 should return rows 1, 2, and 3 because that time falls within the min and max time those 3 rows cover. If I were to pass in 9/21/09 04:20:00, I would expect rows 4 and 5 to be returned.
I started with this query, but that's only going to return rows 2 and 3 (the immediately adjacent rows), not N rows.
SELECT * FROM WINDOW WHERE ABS(DATEDIFF(mi, END, '9/21/09 02:00:00')) <= 10 OR ABS(DATEDIFF(mi, START, '9/21/09 02:00:00')) <= 10
And I tried another approach, but this will return rows 4 and 5 too when I only want 1, 2, and 3 ![]()
SELECT * FROM WINDOW w WHERE EXISTS(SELECT TOP 1 ID FROM WINDOW w2 WHERE w2.ID != w.ID AND ABS(DATEDIFF(mi, w2.END, w.START)) <= 10 OR ABS(DATEDIFF(mi, w2.START, w.END)) <= 10)
Grr
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.