找到最繁忙的时期

时间:2013-07-09 08:05:58

标签: sql tsql sql-server-2012

我在MS SQL 2012(40m记录)中有一个包含呼叫数据的大表。我想找到呼叫的峰值量及其发生的时间。如果可能的话,我还想找到接下来的4个最繁忙时期。

我计划使用3列: 呼叫标识 DialTime 结束时间

我能想到的唯一方法就是这样做:

Select '2013-07-01 00:00:01' as [Period], count([CallID]) as [Calls]
from [Table]
where DialTime <= '2013-07-01 00:00:01'
and EndTime >= '2013-07-01 00:00:01'

union

Select '2013-07-01 00:00:02' as [Period], count([CallID]) as [Calls]
from [Table]
where DialTime <= '2013-07-01 00:00:02'
and EndTime >= '2013-07-01 00:00:02'

union

etc

有人能建议更好/更有效的方法吗?

2 个答案:

答案 0 :(得分:0)

尝试这样的事情。 @time_begin@time_end是您可以用于获得结果的时间间隔的参数。

with time_items (time_item) as
(
    select @time_begin as time_item
    union all
    select dateadd(second,1,t.time_item) as time_item from time_items t where t.time_item<@time_end
)
select
    time_items.time_item as [Period],
    sum(case when [Table].DialTime<=time_items.time_item and [Table].EndTime>=time_items.time_item then 1 else 0 end) as [Calls]
from time_items
left outer join [Table] on 1=1
group by
    time_items.time_item
order by
    [Calls] desc;

答案 1 :(得分:0)

您可以将VALUES用作表源

SELECT DialTime, EndTime, o.Calls
FROM (VALUES ('20130701 00:00:01', '20130701 00:00:01'),
             ('20130701 00:00:02', '20130701 00:00:02'))x(DialTime, EndTime)
  CROSS APPLY(
              SELECT COUNT(CallID) AS Calls      
              FROM [Table] t
              WHERE DialTime <= x.DialTime
                AND EndTime >= x.EndTime
              ) o