开发者

T-SQL Query where DateTime Range WHERE conditions are Generate by Another Query

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                   End开发者_JAVA百科Time
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.

WHERE
      StartTime < myEndTimeLimit
  AND EndTime   > myStartTimeLimit

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...

  TableA
INNER JOIN
  TableB
    ON  <some matching condition>
    AND TableA.StartTime < TableB.EndTime
    AND TableA.EndTime   > TableB.StartTime

(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).

  TableA
INNER JOIN
  TableB
    ON  <some matching condition>
    AND TableA.StartTime <  TableB.EndTime
    AND TableA.StartTime >= TableB.StartTime - 30
    AND TableA.EndTime   >  TableB.StartTime

This now gives a 30 day range in which TableA.StartTime could exist, giving much better performance over time.


To use the results from one query to filter the other, it would look something like this:

SELECT StartTime, EndTime
FROM LogEntries
WHERE StartTime > (SELECT Min(TimeColumn) FROM Times)
AND EndTime < (SELECT Max(TimeColumn) FROM Times)

If you want to be more complex, you could create a join on the two tables so that you could pull values from the "Times" table or query statement.


Return these pairs into a temporary table then join the temp table with your main table.


Join your other table to this query.

Then provide extra AND clauses to match the dates.

Provide table structures or query in use for more help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜