需要从数据库中获取每分钟实时实例的数量

时间:2014-02-22 12:02:29

标签: sql sql-server

我有数据库

  • 表名PerformanceUserData
  • 列: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

查询输入是startdate和enddate

如果开始日期是2014年2月21日下午3:51:30,则结束时间是2/21/2014 5:51:30 PM 我需要从下午3点15分到下午3点半每分钟的数据

数据需要

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

1 个答案:

答案 0 :(得分: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