I’m looking for a way to count the distinct periods without gaps students have been absence:
Each time a student turns in an absence I create a record in the absence table, some absences can overlap, some prolong a previous absence.
StuId StrPer EndPer
------ ----------- -----------
111111 2011-01-10 2011-01-15
222222 2011-02-01 2011-02-05
222222 2011-02-06 2011-02-08
333333 2011-04-07 2011-04-14
444444 2011-04-20 2011-04-25
444444 2011-04-23 2011-04-28
111111 2011-05-01 2011-05-03
Now I want to count the number of unique absence periods with gaps, the result should be:
StuId NbrAbs
------ ------
111111 2
222222 1
333333 1
444444 1
111111 has two absence period with a gap between
222222 also has two absence periods but without gap, so it must be considered as 1 absence period
333333 has only 1 absence period
444444 has 2 periods that overlap, also without gap, so it must be considered as 1 absence period
Can anyone help me write a query for this?
Assuming SQL 2005+ this should work: