我正在尝试为电话系统创建利用率图表。我有表格格式的数据集
ID *
StartDate
EndDate
From
To
我想要做的就是让SQL每隔5分钟输出一个情节点列表,所以基本上
一天中每5分钟一次的活动呼叫计数(在StartDate和EndDate之间)。
结果好像是
Date Time Count
2000-01-01 00:00:00 10
2000-01-01 00:05:00 2
2000-01-01 00:10:00 7
有人可以建议一种生成所述数据的方法吗?我在这里不知所措!我一直在思考的东西都涉及创建一个大循环并且每5秒运行一次查询,这看起来非常低效。
我最初想的方法是: -
storedProc GetSamples(SampleStartDate, SampleEndDate)
Create memory table for result data
for every 5mins as sample between SampleStartDate and SampleEndDate
SELECT @SampleCount = COUNT(1) FROM Samples where 5mins BETWEEN StartDate AND EndDate
UPDATE memoryTable SET count=@SampleCount WHERE time = 5mins
end
end
答案 0 :(得分:1)
如果你有一个最近版本的SQL Server(2008+),你应该可以通过加入你的电话记录的CTE来做到这一点,就像这样(CTE base found here):< / p>
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2000-01-01 00:00:00.000'
SET @EndDate = '2000-01-02 00:00:00.000'
;WITH DateSequence( [PlotPointDate] ) AS
(
SELECT @StartDate AS [PlotPointDate]
UNION ALL
SELECT DATEADD(MINUTE, 5, [PlotPointDate] )
FROM DateSequence
WHERE [PlotPointDate] < @EndDate
)
--select result
SELECT
PlotPointDate, COUNT(YourTable.ID) AS TotalActiveCalls
FROM
DateSequence
LEFT JOIN
YourTable ON
YourTable.StartDate <= DateSequence.PlotPointDate AND
(YourTable.EndDate >= DateSequence.PlotPointDate OR YourTable.EndDate IS NULL)
GROUP BY PlotPointDate
OPTION (MaxRecursion 10000)