how could I improve the performance of this query? I must have a 5 minutes partition and I'd like to run this on more than one day, ideally five. I can't run as a stored procedure.
DECLARE @StartDate datetime = '2019-02-11 00:00:00.001'
,@EndDate datetime = '2019-02-13 23:59:59.999';
WITH theDates AS
(SELECT @StartDate as theDate
UNION ALL
SELECT DATEADD(MINUTE, 5, theDate)
FROM theDates
WHERE DATEADD(MINUTE, 5, theDate) <= @EndDate)
SELECT theDate as Time,
(SELECT ISNULL(AVG(CONVERT(BIGINT, (CAST(DATEDIFF(ms, a.stmpmsg, b.stmpmsg) as decimal(38,2))))),0) as avg
FROM db1 as a INNER JOIN db2 as b
ON a.ProcInstLUID = b.ProcInstLUID
and a.integrationId LIKE 'TAG%' and a.integrationid = b.integrationid and a.stepid = 'TAG_1'
and (b.stepid = 'TAG_2' and b.msgstatusdet like 'TAG_3%')
and a.serviceId = 'TAG_4' and b.serviceId = 'TAG_5'
and a.stmpmsg > @StartDate
and a.stmpmsg < @EndDate
and a.stmpmsg < b.stmpmsg
AND DATEPART(DAY, a.stmpmsg) = datepart(DAY,theDate)
AND DATEPART(hh, a.stmpmsg) = datepart(hh,theDate)
AND (DATEPART(n, a.stmpmsg) >= datepart(n,theDate)
and DATEPART(n, b.stmpmsg) < (datepart(n,theDate)+5))
WHERE 1=1
) AS AvgLng
FROM theDates
OPTION (MAXRECURSION 0)
Running on Microsoft Sql Server, last time it take about 17 hours to give me a result.
JOIN, though, you're applying functions to your columns, likeDATEPART. That is going to ruin any SARGability your query have. What is thatJOINactually trying to achieve. It looks like it's trying to join on rows that are between the date, and the date in 5 minutes? Also, due to the fact it's in a subquery, means that subquery is going to be reevaluated for every row. For the sample we have, that means it's going to be evaluated 865 times!