How do I write a T-SQL query where the filter conditions of datetime ranges are generated from another query.
For Example Query A would Return:
StartTime EndTime
2011-07-06 04:05:42.137 2011-07-06 04:05:58.503
2011-07-06 04:25:51.103 2011-07-06 04:26:07.017
2011-07-06 04:55:56.240 2011-07-06 04:56:04.480
...
How would I return all results that are within the starttime and endtime pairs?
This WHERE clause will return all records that overlap with a specific window of time.
Note: Depending on whether your endTimes are inclusive (up to and Including that moment) or excluse (Everything Before that moment) you may need <= and >= rather than < and >.
Equally, this can be part of a join…
(TableB could be a sub-query)
Note: This type of query is Exceptionally poor in terms of optimisation with an Index.
If you have a year’s worth of data, and you look for an overlap with “today”, the first condition (A.Start < B.End), nearly all of the records are returned, and then scanned to match with (A.End > B.Start).
The simplest optimisation is to “know” the maximum length of any window of time. If all entries are ALWAYS less than 30 days, you could do the following (Amend for your RDBMS’s notation).
This now gives a 30 day range in which TableA.StartTime could exist, giving much better performance over time.