0

我有以下查询:

    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)
4

2 回答 2

0

我认为您可以用表上的窗口函数替换它di(在此处作为子查询完成)。请注意,该where子句不在子查询中,因为这会影响用于的行max()(这可能是您的第二个查询中的问题):

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 (select di.*,
                       max(Entered_On) over (partition by LocId, ParamId) as maxeo
                from data_Input di
               ) 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 = di.maxeo and
          di.Entered_On < (GETUTCDATE() -  dlp.FreqDays)
于 2013-08-07T16:26:38.823 回答
0

尝试像这样使用 -

select ParamID,
   ParamName,
   LocationID,
   LocationName,
   DateEntered,
   Frequency
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 di.LocID order by di.Entered_On desc) as rn
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))
) as T
where rn = 1 
于 2013-08-07T16:37:24.967 回答