I have the following T-SQL Query:
SELECT Wk.WeekID,
Wk.WeekStart,
SUM(CASE WHEN NOT(Task.WeekDate IS NULL) THEN 1 ELSE 0 END) AS WeekCount,
SUM(CASE WHEN NOT(Task.DayDate IS NULL) THEN 1 ELSE 0 END) AS DayCount
FROM tblPerWeek AS Wk
LEFT OUTER JOIN tblPerTask AS Task ON (Task.WeekDate = Wk.WeekStart)
OR (Task.DayDate BETWEEN Wk.WeekStart AND Wk.WeekEnd)
WHERE (Wk.WeekStart <= @DateEnd) AND (Wk.WeekEnd >= @DateStart)
GROUP BY Wk.WeekID, Wk.WeekStart
The structure of tblPerWeek table:
WeekID int
WeekStart date
WeekEnd date
The structure of tblPerTask table:
TaskID int
WeekDate date
DayDate date
Basically, the query counts tasks assigned to week (WeekCount) or specific day inside week (DayCount).
The tblPerWeek has about 2800 records and tblPerTask has about 70000 records.
Now, there is some problem/glitch with (Task.DayDate BETWEEN Wk.WeekStart AND Wk.WeekEnd) condition in join:
- Without this condition in join the query completes instantly
- With this condition in join the query takes about 12 seconds to run
What is the catch? Any solutions on how to make this query faster?
orso that's not going to be good. Is the first half of it redundant?(Wk.WeekStart <= @DateEnd) AND (Wk.WeekEnd >= @DateStart)withWk.WeekStart between dateadd(dd, -6, @DateStart) and @DateEnd?? Looks like you're trying to catch partial weeks or something but I'm not really sure.@DateStartand@DateEndoccupy more than one week, in fact, i was testing 50 years range.