Using SQL Server 2005
Leave Table
ID StartDate EndDate
001 04/01/2010 04/02/2010
002 04/02/2010 04/03/2010
…
Event Table
ID Date PresentDate Status
001 03/30/2010 03/30/2010 Present
001 03/31/2010 null absent
001 04/01/2010 null Leave
001 04/02/2010 null Leave
001 04/03/2010 null absent
001 04/04/2010 04/04/2010 Present
….
All the Datecolumn datatype is datetime
In the Status Column, if Present Date is null then it will display as “absent”, if not null then it will display as “present”. Now if we apply a leave for the date then it will display as “Leave” in status column.
Query
Select
id, date, present date
, CASE WHEN t2.id IS NULL THEN t1.Status ELSE ‘Leave’ END AS status
from event table as t1
left outer join leave table as t2 on
t1.id = t2.id and t1.date between t2.startdate and t2.enddate
The above method is working, but I need to add one more condition.
Once if we applied the leave for the particular employee in the Leave Table then it should compare the Present Date column, if Present Date Column is empty then it should display as “leave”
Expected Output
ID Date PresentDate Status
001 03/30/2010 03/30/2010 Present
001 03/31/2010 null absent
001 04/01/2010 null Leave
001 04/02/2010 null Leave
001 04/03/2010 null Leave (Expect this value)
001 04/04/2010 04/04/2010 Present
….
From the above output Leave is starting from 04/01/2010 to 04/02/2010, then next column of present date is null then status should display as a “Leave”, once present date is not null then it should display as “Present.
Method
We can display as "Leave" in status column from Start Date to end date of leave table, after that leave date end then we can compare with PresentDate column, if PresentDate column is null then it should display as "Leave", once data is available in present column then status should display with normal condition.
How to make a query for the above condition.
Need Query Help
Leave table
Output
The ones marked -** are not covered by Leave records, but they show leave because they follow a Leave period, correct?
2010-04-09for example remains “Absent” because it follows a Present record (without actually being present).