我有以下查询。我做的部分
select for max(Entered_On).....
耗时最长。如果我注释掉 where 原因,它会运行得很快。
Select dlp.ParamID, dp.ParamName
from data_LocP dlp
inner join data_In di on dlp.LocID = di.LocID
inner join data_Parms dp on dp.ParamID = di.ParamID
inner join map_Loc ml on ml.LocId = dlp.LocId
where di.Entered_On = (select max(Entered_On ) from data_In where LocId = dlp.LocID
and ParamId = dlp.ParamID)
我想知道是否有办法优化这个查询,因为我得到 Max(Entered_On) 的部分花费的时间最长。作为一个仅供参考,我需要 Entered_On 作为给定 LocId 和 ParamId 的最大日期。
这是一个更扩展的代码,但没有给出最大值:
select * FROM
(
SELECT dlp.ParamID, dp.ParamName, dlp.LocID, ml.LocName , di.Entered_On, (GETUTCDATE() - dlp.FreqDays) DueDate, dlp.FreqDays,
a.CompanyId, a.SiteID,
ROW_NUMBER() OVER (PARTITION BY dlp.LocId, dlp.ParamID
ORDER BY di.Entered_On DESC)
as RowNum
from data_LocParams dlp
inner join data_Input di on dlp.LocID = di.LocID
inner join data_Parameters dp on dp.ParamID = di.ParamID
inner join map_Locations ml on ml.LocId = dlp.LocId
left join
(
select ml.LocId,ms.CompanyId, ms.SiteId
from map_Sites ms
join map_WaterSystems mw
on ms.SiteID = mw.SiteID
join map_Locations ml
on ml.SysID = mw.SysID
) a
on a.LocId = dlp.LocID
where dlp.FreqDays is not null AND dlp.FreqDays <> ''
) as a WHERE a.RowNum = 1 and Entered_On < (GETUTCDATE() - FreqDays)