0

在其他人的帮助下,我有了这个 sql 语句来计算表中记录之间的里程差(+ 或 -)。问题是,当我向计算值添加标准(> 0)时,它会大大减慢我的查询速度。如果我向任何其他字段添加条件,那么事情会按预期运行(不会长时间延迟)。

SELECT T1.Date, 
       T1.Route, 
       T1.BookingID, 
       T1.StreetNumber, 
       T1.Street, 
       T1.Arrive, 
       T1.Perform, 
       T1.Miles, 
       T1.Miles - (SELECT Miles 
                   FROM   Test1 AS T2 
                   WHERE  T2.Route = T1.Route 
                          AND T2.IDNumber = (SELECT Min(IDNumber) 
                                             FROM   Test1 AS T3 
                                             WHERE  T3.Route = T1.Route 
                                                    AND T3.IDNumber > 
                                                        T1.IDNumber)) AS 
       Difference 
FROM   Test1 AS T1 
GROUP  BY T1.Date, 
          T1.Route, 
          T1.BookingID, 
          T1.StreetNumber, 
          T1.Street, 
          T1.Arrive, 
          T1.Perform, 
          T1.Miles, 
          T1.IdNumber, 
          T1.Status, 
          T1.Activityy 
HAVING (( ( [T1].[Miles] - (SELECT Miles 
                            FROM   Test1 AS T2 
                            WHERE  T2.Route = T1.Route 
                                   AND T2.IDNumber = (SELECT Min(IDNumber) 
                                                      FROM   Test1 AS T3 
                                                      WHERE  T3.Route = T1.Route 
                                                             AND T3.IDNumber > 
                                                     T1.IDNumber)) ) > 0 )) 
ORDER  BY T1.IdNumber; 
4

1 回答 1

0

您的不同之处在于找到下一个里程记录。

如果您的数据库支持 row_number() 或 lag(),那么您可以使用 windows 函数而不是多个自联接来重写此查询。那应该可以解决性能问题。

否则,重写查询,使连接位于“from”子句中。这也应该解决问题。

最后,如果要使用临时表,请将所有结果放在临时表中,然后进行选择。(这不是我的首选方法,但对于一次性查询,它可能是最快的解决方案。)

于 2012-05-10T20:34:34.663 回答