cmwarre
cmwarre

Reputation: 117

SQL Server : filter on dates from another table

I'm pretty new to SQL Server so this may be a pretty easy question

I have a log table view that looks like the following:

enter image description here

And a table that logs the start and stop of a run that looks like the following:

enter image description here

I would like to filter data from the first table between the start and stop times in the second table. Is there any way to do that?

Upvotes: 1

Views: 1171

Answers (1)

Andomar
Andomar

Reputation: 238078

You can use a regular join to match a date-range:

select  *
from    Entries e
join    Runs r
on      r.StartTime <= e.EntryTime
        and (
          e.EntryTime <= r.StopTime
          or r.StopTime is null -- For a run that has not yet stopped
        )

But your example data suggests there is a foreign key, which would eliminate the need for date-range matching:

select  *
from    Entries e
join    Runs r
on      e.ProjectRunId = r.ProjectRunId

Upvotes: 1

Related Questions