как я могу улучшить производительность этого запроса?У меня должен быть 5-минутный раздел, и я хотел бы запустить его более чем на один день, в идеале на пять.Я не могу запустить как хранимую процедуру.
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)
Работает на Microsoft Sql Server, в прошлый раз для получения результата понадобилось около 17 часов.