CREATE TABLE #TEMPTABLE
(
requestTime datetime2,
NoOfSessions integer
)
INSERT INTO #TEMPTABLE
select convert(nvarchar(16), TimeLog, 120) requestTime , COUNT(DISTINCT SessionId)As NoOfSessions
from LogData
group by convert(nvarchar(16), TimeLog, 120) order by requestTime;
select s1.requestTime
, (
select sum(NoOfSessions)
from #TEMPTABLE s2
where dateadd(minute, -15, s1.requestTime) < s2.requestTime
and s2.requestTime <= s1.requestTime
) as TotalNumberOfSessions
from #TEMPTABLE s1
DROP TABLE #TEMPTABLE
答案 0 :(得分:1)
试试这个并告诉我。这对你来说可能有所改善。
我在临时表中的requestTime
添加了一个主键,可以在相关的子查询中使用。
create table #TEMPTABLE
(
requestTime smalldatetime primary key,
NoOfSessions integer
)
insert into #TEMPTABLE
select dateadd(minute, datediff(minute, 0, TimeLog), 0),
count(distinct SessionId)
from LogData
group by dateadd(minute, datediff(minute, 0, TimeLog), 0)
select s1.requestTime
, (
select sum(NoOfSessions)
from #TEMPTABLE s2
where dateadd(minute, -15, s1.requestTime) < s2.requestTime
and s2.requestTime <= s1.requestTime
) as TotalNumberOfSessions
from #TEMPTABLE s1
drop table #TEMPTABLE
答案 1 :(得分:0)
一般来说,问题可能是:
其中dateadd(分钟,-15,s1.requestTime)&lt; s2.requestTime
我不确定这会导致有效的查询计划 - 但是您没有向我们展示该计划。
答案 2 :(得分:0)
临时表不是问题。问题是相关的子查询导致了一系列疯狂的循环连接迭代。
尝试将子查询重新配置为连接。将datetime值四舍五入为分钟并加入分钟值。
答案 3 :(得分:0)
我认为临时表不是问题所在,但这是没有它的代码:
select s1.requestTime
, (
select sum(NoOfSessions)
from
(
select dateadd(minute, datediff(minute, 0, TimeLog), 0),
count(distinct SessionId)
from LogData
group by dateadd(minute, datediff(minute, 0, TimeLog), 0)
) s2
where dateadd(minute, -15, s1.requestTime) < s2.requestTime
and s2.requestTime <= s1.requestTime
) as TotalNumberOfSessions
from
(
select dateadd(minute, datediff(minute, 0, TimeLog), 0),
count(distinct SessionId)
from LogData
group by dateadd(minute, datediff(minute, 0, TimeLog), 0)
) s1