I have a table valued function to count student truant days in any passed 30 days that met threshold of 7 days and return the earliest passed threshold date.I have to use a recursive CTE in the table valued function to count these. The truant table will have records for each student , each absent date.The table valued function is run every day, because the TruantDay table is updated every day with new attendance data in case student is excused from absent.Currently the query runs fine, it takes about 20 seconds. But I am a little worried it will increase as the TruantDay table increased. If anything to improve for the speed? WITH FirstLastAbsentDates AS( SELECT a.StudentId ,MIN(a.Att_Date) AS FirstDay ,MAX(a.Att_Date) AS EndDay FROM TruantDay a WHERE a.IsAbsent = 1 AND a.IsCleared = 0 GROUP BY a.StudentId HAVING MAX(a.Att_Date) > MIN(a.Att_Date)), CTEDateRanges (StudentId, EndDay) AS( SELECT a.StudentId ,a.EndDay FROM FirstLastAbsentDates a UNION ALL SELECT a.StudentId ,DATEADD(d, -1, c.EndDay) AS EndDay FROM FirstLastAbsentDates a JOIN CTEDateRanges c ON c.StudentId = a.StudentId WHERE DATEADD(d, -1, c.EndDay) > a.FirstDay), MTDOver6Days AS(SELECT a.StudentId , a.EndDay AS ThresholdDate , COUNT(*) AS AbsenceCountFROM CTEDateRanges aJOIN TruantDay b ON b.StudentId = a.StudentIdWHERE b.IsAbsent = 1 AND b.IsCleared = 0 AND b.Att_Date BETWEEN DATEADD(d, -30, a.EndDay) AND a.EndDayGROUP BY a.StudentId, a.EndDayHAVING COUNT(*) > 6)SELECT a.StudentId ,a.ThresholdDate ,a.AbsenceCountFROM MTDOver6Days aWHERE a.ThresholdDate = (SELECT MIN(b.ThresholdDate) FROM MTDOver6Days b WHERE b.StudentId = a.StudentId
↧