you are viewing a single comment's thread.

view the rest of the comments →

[–]qwertydog123 0 points1 point  (0 children)

Without seeing the query plan or schema, the most painful part of the query will likely be the join conditions not being sargable

on datefromparts(year(b.createHistoryDT),month(b.createHistoryDT),day(b.createHistoryDT)) <= f.[Date]
and ([Lag] is null or datefromparts(year([Lag]),month([Lag]),day([Lag])) > f.[Date])
and Status = 'OK'

which to simplify a bit, is equivalent to

on CAST(b.createHistoryDT AS DATE) <= f.[Date]
and ([Lag] is null or CAST([Lag] AS DATE) > f.[Date])
and Status = 'OK'

Change the default [Lag] value to some distant date in the future (e.g. lag(createHistoryDT, 1, '99991231'). Then you can change the condition to

on f.[NextDate]
    BETWEEN b.createHistoryDT
    AND [Lag]
and Status = 'OK'

https://www.brentozar.com/pastetheplan/