在SQL Server中,我試圖拼湊其抓住一排單查詢,包括來自該行前兩個小時的窗口中的彙總數據,以及從一個聚合數據小時後窗口。我怎樣才能讓這個運行更快?加快SQL服務器跨應用獲得彙總數據
的行具有時間戳的毫秒精度,而不是均勻地隔開。我在此表中有50萬行,並且查詢似乎沒有完成。許多地方都有索引,但它們似乎沒有幫助。我也在考慮使用窗口函數,但我不確定它是否可能具有不均勻分佈的行的滑動窗口。另外,對於未來的一個小時窗口,我不確定如何用SQL窗口完成這個工作。
Box是一個字符串,有10個獨特的價值觀。 進程是一個字符串,有30個唯一值。 平均duration_ms是200毫秒。 錯誤數據少於0.1%。 5000萬行描述了數年的數據。
select
c1.start_time,
c1.end_time,
c1.box,
c1.process,
datediff(ms,c1.start_time,c1.end_time) as duration_ms,
datepart(dw,c1.start_time) as day_of_week,
datepart(hour,c1.start_time) as hour_of_day,
c3.*,
c5.*
from metrics_table c1
cross apply
(select
avg(cast(datediff(ms,c2.start_time,c2.end_time) as numeric)) as avg_ms,
count(1) as num_process_total,
count(distinct process) as num_process_unique,
count(distinct box) as num_box_unique
from metrics_table c2
where datediff(minute,c2.start_time,c1.start_time) <= 120
and c1.start_time> c2.start_time
and c2.error_code = 0
) c3
cross apply
(select
avg(case when datediff(ms,c4.start_time,c4.end_time)>1000 then 1.0 else 0.0 end) as percent_over_thresh
from metrics_table c4
where datediff(hour,c1.start_time,c4.start_time) <= 1
and c4.start_time> c1.start_time
and c4.error_code= 0
) c5
where
c1.error_code= 0
編輯
版:SQL Azure的12.0
如果性能問題不是因爲您的where謂詞,我會感到驚訝。你的where子句中有函數,這意味着你必須爲每一行計算datediff。在這種情況下,你正在做兩次。這意味着你正在執行大約1億次的計算。 –
@Hogan我試圖去開窗,但是我沒有看到一種方法,如果數據點不是以均勻間隔收集的話,我會從某個時間點開始-2小時。含義從一排的差到下一個可能是幾毫秒,可能是幾秒鐘,可能是幾分鐘 – user4446237
是的,這是不可能在SQL Server實現(沒有'範圍介於INTERVAL'),你就必須做一些預聚合以保證每分鐘一行等。但是'COUNT(DISTINCT ...)'不容易兼容。 –