更好的PARTITION BY解决方案?

时间:2014-03-11 11:47:44

标签: sql tsql

我想优化这个

WITH a as
(SELECT *
       ,ROW_NUMBER()  OVER (PARTITION BY applicationid ORDER BY AgreementStartDate desc) rn
       ,(select count(*) from RM_TbPackages where d.ApplicationID=ApplicationID) as PackageCount 
 FROM CM_VwSupplierApplications d)
select * from a
where rn=1
order by a.ApplicationID

1 个答案:

答案 0 :(得分:1)

此查询将运行得更快,因为它没有为CM_VwSupplierApplications中的任何行进行子选择:

;WITH a AS
(
SELECT * ,ROW_NUMBER()  OVER (PARTITION BY applicationid ORDER BY AgreementStartDate desc) rn
FROM CM_VwSupplierApplications d
)
SELECT a.*, b.PackageCount
FROM a
OUTER APPLY
(  SELECT count(*) PackageCount 
   FROM RM_TbPackages 
   WHERE d.ApplicationID=ApplicationID) b
WHERE a.rn=1
ORDER BY a.ApplicationID

为了进一步改进,您可以考虑列applicationid和AgreementStartDate上的表CM_VwSupplierApplications上的索引