有问题的sql server查询

时间:2011-08-30 21:52:30

标签: sql sql-server greatest-n-per-group

我有以下查询运行缓慢:

 WITH AcdTran
     AS (select SequenceNo,
                ReqID,
                PolNumber,
                transaction_id,
                application_data,
                trans_type,
                retries,
                status,
                direction
         from   dbo.acord_transaction_benchmark with (nolock)
         where  direction = 'OUT')
select top 1 *
from   AcdTran a
where  a.transaction_id = (select top 1 transaction_id
                           from   AcdTran b
                           where  b.PolNumber = a.PolNumber
                           order  by ReqID,
                                     SequenceNo,
                                     transaction_id)
       and ( status = 'New'
              or status = 'Resubmit' )
       and retries > 0  

我如何优化这个?跑得更快?

谢谢

2 个答案:

答案 0 :(得分:2)

窗口函数ROW_NUMBER应该更快:

 WITH AcdTran AS (
         SELECT SequenceNo,
                ReqID,
                PolNumber,
                transaction_id,
                application_data,
                trans_type,
                retries,
                status,
                direction,
                ROW_NUMBER() OVER(PARTITION BY transaction_id ORDER BY ReqID, SequenceNo, transaction_id) N
           FROM dbo.acord_transaction_benchmark with (nolock)
          WHERE direction = 'OUT')
SELECT *
  FROM AcdTran
 WHERE (status = 'New'
            OR status = 'Resubmit')
       AND retries > 0
       AND N = 1;

由于我没有您的表结构或任何数据,我显然没有测试它,所以您可能需要稍微修改一下查询,但您有这个想法。

答案 1 :(得分:0)

如果您将子查询提取到联接中,该怎么办:

WITH AcdTran
     AS (select SequenceNo,
                ReqID,
                PolNumber,
                transaction_id,
                application_data,
                trans_type,
                retries,
                status,
                direction
         from   dbo.acord_transaction_benchmark with (nolock)
         where  direction = 'OUT')
select top 1 *
from   AcdTran a
inner join AcdTran b on a.SequenceNo = b.SequenceNo --or whatever the PK is
where a.transaction_id = b.transaction_id and
      a.PolNumber = b.PolNumber and
      (a.status = 'New' or a.status = 'Resubmit' ) and
      a.retries > 0
order by b.ReqID,
         b.SequenceNo,
         b.transaction_id