以下示例查询是我的主查询的一部分。我在下面的查询中发现SORT运算符消耗了30%的成本。
要避免SORT,需要创建索引。有没有其他方法来优化此代码。
SELECT TOP 1 CONVERT( DATE, T_Date) AS T_Date
FROM TableA
WHERE ID = r.ID
AND Status = 3
AND TableA_ID >ISNULL((
SELECT TOP 1 TableA_ID
FROM TableA
WHERE ID = r.ID
AND Status <> 3
ORDER BY T_Date DESC
), 0)
ORDER BY T_Date ASC
答案 0 :(得分:1)
看起来您可以使用not exists
而不是排序。我认为通过使用CTE或派生表而不是标量子查询,你可能会获得更好的性能提升。
select *
from r ... left outer join
(
select ID, min(t_date) as min_date from TableA t1
where status = 3 and not exists (
select 1 from TableA t2
where t2.ID = t1.ID
and t2.status <> 3 and t2.t_date > t1.t_date
)
group by ID
) as md on md.ID = r.ID ...
或
select *
from r ... left outer join
(
select t1.ID, min(t1.t_date) as min_date
from TableA t1 left outer join TableA t2
on t2.ID = t1.ID and t2.status <> 3
where t1.status = 3 and t1.t_date < t2.t_date
group by t1.ID
having count(t2.ID) = 0
) as md on md.ID = r.ID ...
您似乎还依赖于标识列,但不清楚这些值的含义。我基本上忽略它并改为使用日期列。
答案 1 :(得分:0)
试试这个:
SELECT TOP 1 CONVERT( DATE, T_Date) AS T_Date
FROM TableA a1
LEFT JOIN (
SELECT ID, MAX(TableA_ID) AS MaxAID
FROM TableA
WHERE Status <> 3
GROUP BY ID
) a2 ON a2.ID = a1.ID AND a1.TableA_ID > coalesce(a2.MAXAID,0)
WHERE a1.ID = r.ID AND a1.Status = 3
ORDER BY T_Date ASC
将TOP 1
与不明原因的r
别名结合使用会引起我的注意。几乎可以肯定的是, MUCH 更好的方法是将这些数据导入到您的结果中并不涉及在子查询中执行此操作(除非这是针对APPLY
操作)。