Hi @Wayne Bartkowski
Here are some tips:
- Replace a complex statement with multiple simple statements.
For example, create a temporary table and insert the result set of the first CTE into it. - Make sure all mentioned columns are indexed, especially filter columns.
- Avoid too many CASE WHEN expressions in the recursive CTE. You could move the first two CASE WHEN expressions outside of the recursive CTE, like this: ;with cte as
( -- SQL recursive CTE expression
select -- anchor query
[TheDate],
asset_id,
[created_date1],
'' as [created_date2],
[completed_datetime1],
'' as [completed_datetime2],
rn,
1 as GroupId
from timePeriods
where rn = 1 union all select -- recursive sql query
p1.TheDate,
p1.[asset_id],
p1.[created_date],
p2.[created_date],
p1.[completed_datetime],
p2.[completed_datetime],
p2.rn,
case when
(p1.[created_date] between p2.[created_date] and p2.[completed_datetime]) or
(p1.[completed_datetime] between p2.[created_date] and p2.[completed_datetime]) or
(p1.[created_date] < p2.[created_date] and p1.[completed_datetime] > p2.[completed_datetime]) or
(p1.[created_date] > p2.[created_date] and p1.[completed_datetime] < p2.[completed_datetime])
then p1.GroupId else (p1.GroupId+1) end as GroupId
from cte p1 inner join timePeriods p2 on p1.[asset_id] = p2.[asset_id] and (p1.rn+1) = p2.rn
)
select TheDate,[asset_id],
case
when ([created_date1] between [created_date2] and [completed_datetime2]) then [created_date2]
when ([created_date2] between [created_date1] and [completed_datetime1]) then [created_date1]
when ([created_date1] < [created_date2] and [completed_datetime1] > [completed_datetime2]) then [created_date1]
when ([created_date1] > [created_date2] and [completed_datetime1] < [completed_datetime2]) then [created_date2]
else [created_date2] end as [created_date],
,etc
from cte
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.