Skip to content
Advertisement

Join query on Date Range

HI
I have following tables

=========================
Periods
=========================
PeriodID  StartDate   EndDate
1         01-01-11    07-01-11
2         08-01-11    15-01-11

and so on for whole year

=========================
History
=========================
PersonID  From       To
1         01-01-11  05-04-11
2         17-06-11   NULL 
and so on

I want the following output

 StartDate   EndDate   PersonID
  01-01-11    07-01-11    1
  08-01-11    15-01-11    1
  .
  .
  15-04-11   21-04-11     NULL
  .
  .
  15-06-11   21-06-11     2

I need to take join between these two tables but i couldn’t figure how join condition will be look like

Ragards

Advertisement

Answer

SELECT
  p.StartDate,
  p.EndDate,
  h.PersonID
FROM Periods p
  LEFT JOIN History h
    ON h.[From] BETWEEN p.StartDate AND p.EndDate OR
       p.StartDate BETWEEN h.[From] AND ISNULL(h.[To], '30000101')
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement