2014-02-22 86 views
1

獲取每分鐘活動實例的數量我有數據庫需要從數據庫

Table name PerformanceUserData 
Coulumns (StartDate as datetime, enddate as datetime,ip address, instance) 

對於每一行實例值是1。

的樣本數據是

2/21/2014 10:39:17 AM 2/21/2014 10:40:24 AM 192.168.1.51 1 
2/21/2014 10:40:24 AM 2/21/2014 10:41:57 AM 192.168.1.51 1 
2/21/2014 3:51:29 PM 2/21/2014 3:51:30 PM 192.168.1.12 1 
2/21/2014 3:51:30 PM 2/21/2014 3:52:06 PM 192.168.1.12 1 
2/21/2014 3:52:06 PM 2/21/2014 3:52:39 PM 192.168.1.12 1 
2/21/2014 3:52:39 PM 2/21/2014 3:53:12 PM 192.168.1.12 1 

輸入到查詢開始日期和結束日期 如果開始日期是2014年2月21日3:51:30,並且enddate是2014/2/21 5:51:30我需要每分鐘從下午3點15分到下午3點16分的數據

數據需要

Time    number of instances 
3.51 to 3.52  2 
3.52 to 3.53  2 
+0

還有,你試過嗎? –

+0

我們已經建立了目錄並將所有條目推入其中,然後在其他表上進行連接但是這需要很長時間 – user2478625

回答

1

@gordon是不錯。很迷惑律約樣本數據, 嘗試這樣的事情,

Declare @PerformanceUserData Table(StartDate datetime, enddate datetime,ip varchar(20), instance int) 
insert into @PerformanceUserData 
select '2/21/2014 10:39:17 AM','2/21/2014 10:40:24 AM','192.168.1.51', 1 union all 
select '2/21/2014 10:40:24 AM','2/21/2014 10:41:57 AM','192.168.1.51',1 union all 
select '2/21/2014 3:51:29 PM','2/21/2014 3:51:30 PM','192.168.1.12',1 union all 
select '2/21/2014 3:51:30 PM','2/21/2014 3:52:06 PM','192.168.1.12',1 union all 
select '2/21/2014 3:52:06 PM','2/21/2014 3:52:39 PM','192.168.1.12',1 union all 
select '2/21/2014 3:52:39 PM','2/21/2014 3:53:12 PM','192.168.1.12',1 
--select * from @PerformanceUserData 
Declare @startdate datetime='2/21/2014 3:51:30 PM' 
Declare @enddate datetime='2/21/2014 5:51:30 PM' 
Declare @t Table(dates datetime, rn int) 
;with cte as 
(
select @startdate dates, 
1 rn 
union all 
select DATEADD(minute,1,dates),rn+1 from cte where dates<@enddate 
) 

insert into @t 
select * from cte option(maxrecursion 0) 

select a.dates,b.dates 
,(select count(*) from @PerformanceUserData where StartDate 
between a.dates and b.dates)[number of instances] 
from @t a inner join @t b on b.rn-a.rn=1