0

我有以下查询。我做的部分

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

3 回答 3

4

尝试使用ROW_NUMBER()而不是相关子查询:

SELECT * FROM (
  SELECT   dlp.ParamID, dp.ParamName, 
           ROW_NUMBER() OVER (PARTITION BY dlp.LocId, dlp.ParamID 
                              ORDER BY di.Entered_On) as RowNum
  FROM data_LocP  dlp 
  JOIN data_In  di on dlp.LocID = di.LocID
  JOIN data_Parms dp on dp.ParamID = di.ParamID
  JOIN map_Loc ml on ml.LocId =  dlp.LocId
) WHERE RowNum = 1

如果您有多个可以匹配相同Entered_On值的记录,请使用RANK()而不是ROW_NUMBER().

于 2013-08-06T19:10:12.790 回答
1

除了对 SQL SELECT 进行任何更改之外,请尝试Entered_OnDESC顺序构建索引。这应该有助于任何需要在 Entered_On DESC 上排序或拉取 MAX 的 Entered_On 的查询。

CREATE NONCLUSTERED INDEX idx_entered_on ON data_in
(
    LocId, ParamId, Entered_On DESC
)
于 2013-08-06T20:29:07.790 回答
0

您说“我需要 Entered_On 成为给定 LocId 和 ParamId 的最大日期”,但您没有为这些字段指定任何值。就像是:

where locId = something
and ParamId = something

在主查询和子查询中都会得到你想要的,并且会很快做到。

于 2013-08-06T19:18:33.383 回答