0

我在下面有这个非常冗长的查询。我在运行它时遇到问题,因为它需要很长时间并且一直在我身上超时:

    with t as 
   (
select a.ID, 
       a.Date_Reported AS [Date Sent],  
       b.Date_Received AS [Date Returned], 

(datediff(dd, a.date_reported, b.date_received) 
      + CASE WHEN Datepart(dw, b.date_received) = 7 THEN 1 ELSE 0 END 
       - (Datediff(wk, a.date_reported, b.date_received) * 2 ) 
       - CASE WHEN Datepart(dw, b.date_received) = 1 THEN 1 ELSE 0 END + 
       - CASE WHEN Datepart(dw, b.date_received) = 1 THEN 1 ELSE 0 
       END) AS [Overall_Time_Spent]

from [Transactions_External] a 
join [Transactions] b on b.id like '%'+a.id+'%'
where a.customer = 'AA'
AND a.Date_Reported >= DATEADD(MONTH,-1,DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()),0))
AND a.Date_Reported <  DATEADD(d,1,EOMONTH(GETDATE(),-1)) 
AND a.ID IS NOT NULL
AND a.ID <> ''
AND b.ID not like '%_H'

    )


    select V.*
    from 
    (
        select 
           sum(case when Overall_Time_Spent < 0 then 1 else 0 end) as Errors,
           sum(case when Overall_Time_Spent between 0 and 3 then 1 else 0 end) as _0_3_days,
           sum(case when Overall_Time_Spent = 4 then 1 else 0 end) as _4_days,
           sum(case when Overall_Time_Spent = 5 then 1 else 0 end) as _5_days,
           sum(case when Overall_Time_Spent between 6 and 8 then 1 else 0 end) as _6_8_days,
           sum(case when Overall_Time_Spent >= 9 then 1 else 0 end) as more_than_9_days,
           count(Overall_Time_Spent) as Total
    from t

    ) T1
    cross apply 
    ( values 
      ('Count', convert(int, [Errors]), convert(int, [_0_3_days]), convert(int, [_4_days]), convert(int, [_5_days]), convert(int, [_6_8_days]),  convert(int, [more_than_9_days]), convert(int, [Total]))
      )
    v([Time Taken (days)], [Errors], [0-3],[4],[5],[6-8],[9+], [Total])

该查询本质上是查看两个表,加入 id (这在任何一个表上都略有不同,因此在加入时类似),然后找到两个日期的差异以找到总花费的时间。然后稍后将时间分为多个范围。查询仅限于上个月。

我可以做些什么来使它运行得更快或更改查询以帮助它运行得更快。我认为问题可能出在原始选择中:

datediff(dd, a.date_reported, b.date_received) 
      + CASE WHEN Datepart(dw, b.date_received) = 7 THEN 1 ELSE 0 END 
       - (Datediff(wk, a.date_reported, b.date_received) * 2 ) 
       - CASE WHEN Datepart(dw, b.date_received) = 1 THEN 1 ELSE 0 END + 
       - CASE WHEN Datepart(dw, b.date_received) = 1 THEN 1 ELSE 0 
       END) AS [Overall_Time_Spent]

我可能会选择所有数据库而不是上个月?

需要注意的一件重要事情是我无法创建任何表或拆分查询 - 所以我真的需要运行选择并在一个查询中完成。我不确定这是可能的。

4

1 回答 1

1

不建议先加入like和“%”

join [Transactions] b on b.id like '%'+a.id+'%'

索引不会用于 a.id(如果有),它需要完全扫描。也许尝试对您的查询进行解释以查看扫描的行数

于 2018-06-06T14:05:25.800 回答