I have a query:
with cte as
(
//some select statement
)
select -
// also some code here
from cte a
outer apply
(select top 1 position,traffic,tags,url,Domain,Load_Date,trend_date
from cte b
where b.Date_ID<=a.Date_ID and
b.Load_Date is not null and
a.Domain is null and
a.Project_Id=b.Project_Id and
a.SE_Id=b.SE_Id and
a.Keyword=b.keyword
order by a.Date_ID desc
)x
My cte
returns almost 3 million rows. This query takes a very long time to finish (every 4 minutes it returns only 500 rows)
But the following query without Keyword
compare in outer apply, is very fast:
with cte as
(
//some select statement
)
select
// also some code here
from cte a
outer apply
(select top 1 position,traffic,tags,url,Domain,Load_Date,trend_date
from cte b
where b.Date_ID<=a.Date_ID and
b.Load_Date is not null and
a.Domain is null and
a.Project_Id=b.Project_Id and
a.SE_Id=b.SE_Id and
order by a.Date_ID desc
)x
The Problem is, that I need this Keyword comparison in my query. My question is now, How should I change my original query to have a better performance? good to know:
- Project_Id is
int
- SE_Id is
int
- Keyword is
nvarchar(2000)