我有以下查询:
SELECT dlp.ParamID ParamID, dp.ParamName ParamName, dlp.LocID LocationID, ml.LocName LocationName , di.Entered_On DateEntered, dlp.FreqDays Frequency
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
WHERE ( (dlp.FreqDays IS NOT NULL) AND di.Entered_On < (GETUTCDATE() - dlp.FreqDays))
AND
di.Entered_On = (select max(Entered_On ) from data_Input where LocId = dlp.LocID
and ParamId = dlp.ParamID)
我需要有关如何优化此查询的帮助。瓶颈似乎与以下内容有关:
di.Entered_On = (select max(Entered_On ) from data_Input where LocId = dlp.LocID
and ParamId = dlp.ParamID)
请注意,对于给定的 Enter_On,我需要根据 LocId 和 ParamId 获取 Max Entered_On 日期。
我尝试了以下但没有得到预期的结果:
SELECT * FROM
(
SELECT dlp.ParamID ParamID, dp.ParamName ParamName, dlp.LocID LocationID, ml.LocName LocationName, di.Entered_On DateEntered, dlp.FreqDays Frequency,
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
WHERE dlp.FreqDays IS NOT NULL
) as a WHERE a.RowNum = 1 and DateEntered < (GETUTCDATE() - Frequency)