使用 Group BY MAX 和 JOINED 子查询优化查询 TABLE

Optimize query with a subquery With Group BY MAX and JOINED with another TABLE

我需要帮助来优化此 SQL 查询,以便 运行 更快。

我想做的是,从这些表中获取 DATA 的最新值:

TABLE:引用
ID QuoteNumber LastUpdated(inticks) PolicyId
1 C1000 1000000000000 100
1 D2000 1001111111110 200
2 A1000 1000000000000 300
2 B2000 1002222222222 400

TABLE:政策
ID CustomerName Blah1(虚拟列)
100 标记一些数据
200 丽莎 someData2
300 布雷特 someData3
400 悟空 someData4

期望的结果:
LastUpdated Id(quoteId) QuoteNumber CustomerName
1001111111110- -1- -D2000- -丽莎
1002222222222- -2- -B2000- -悟空

Select DISTINCT subquery1.LastUpdated,
                q2.Id, 
                q2.QuoteNumber,
                p.CustomerName 
                FROM
                (Select q.id, 
                            Max(q.LastUpdated) from Quotes q
                            where q.LastUpdated > @someDateTimeParameter
                            and q.QuoteNumber is not null
                            and q.IsDiscarded = 0
                            GROUP BY q.id) as subquery1
LEFT JOIN Quotes q2
on q2.id = subquery1.id
and q2.LastUpdated = subquery1.LastUpdated
INNER JOIN Policies p
on p.id = q2.PolicyId
where p.blah1 = @someBlahParameter
ORDER BY subquery1.LastUpdated

下面是实际的执行计划: https://www.brentozar.com/pastetheplan/?id=SkD3fPdwD

我想你正在寻找这样的东西

with q_cte as (
    select q.Id, q.QuoteNumber, q.LastUpdated, 
           row_number() over (partition by q.id order by q.LastUpdated desc) rn
    from Quotes q
    where q.LastUpdated>@someDateTimeParameter
          and q.QuoteNumber is not null
          and q.IsDiscarded=0)
select q.*, p.CustomerName 
from q_cte q
     join Policies p on q.PolicyId=p.id
where q.rn=1 /* Only the lastest date */
      and p.blah1=someBlahParameter
order by q.LastUpdated;