Sql – ID should not display between the specified date

sqlsql serversql-server-2000tsql

Using SQL Server 2000

Database1.Table1

ID  Name Date       title    
001 Ravi 23-02-2009 Accountant
001 Ravi 24-02-2009 Accountant
001 Ravi 25-02-2009 Accountant
002 Ram  21-02-2009 Supervisors
002 Ram  25-02-2009 Supervisors
002 Ram  26-02-2009 Supervisors

So on…,

Database2.Table2

ID  Name Date1      Date2    
001 Ravi 23-02-2009 24-02-2009 
002 Ram  21-02-2009 24-02-2009

So on…

Suppose I want to display the records from 21-02-2009 to 26-02-2009 –
Expected Output:

001 Ravi 25-02-2009 Accountant
002 Ram 25-02-2009 Supervisors
002 Ram 26-02-2009 Supervisors

From the above two table I want to display id, name, date, title from Database1.table1 where Database1.table1.id should not display between date1 and date2 from Database2.table2:

(23-02-2009 to 24-02-2009) ID should not display from table1
(21-02-2009 24-02-2009) ID should not display from table1

How to make a query in SQL?

Can any one help me.

Best Answer

For every row in Table1 we look for row in Table2 and show only rows with no Table2 match:

SELECT
  TABLE1.*
FROM TABLE1
LEFT JOIN TABLE2
ON 
  (TABLE1.ID = TABLE2.ID) AND --JOIN TABLE2 BY ID
  (TABLE1.DATE BETWEEN TABLE2.DATE1 AND TABLE2.DATE2) --AND BY DATE CRITERIA
WHERE 
  (TABLE2.ID IS NULL) AND --SHOW ONLY IF IT DIDN'T MATCH ROW IN TABLE2
  (TABLE1.DATE BETWEEN '21-02-2009' AND '26-02-2009')