MSSQL查询:如何每2小时计算一次(动态)?

问题描述 投票:0回答:2

我是这个网站的新手,找不到类似的问题,也不确定这是否有可能在SQL中查询,但是,到底是什么,值得一试......

我有一个访问控制系统,它将条目日志写入我的数据库。从我的数据表中附加样本:

tpxID   Rec_Creation_Date
2995392 2018-03-06 11:50:45.000
2995391 2018-03-06 11:39:48.000
2995390 2018-03-06 11:30:58.453
2995389 2018-03-06 11:30:49.297
2995388 2018-03-06 11:30:30.687
2995387 2018-03-06 11:30:22.547
2995386 2018-03-06 11:30:13.483
2995385 2018-03-06 11:30:04.813
2995384 2018-03-06 11:29:57.640
2995383 2018-03-06 11:29:49.670

我的想法是,我想知道是否有2个小时的时间框架,我有超过200个条目?

我的意思是动态查询,不会只查看整个小时。

不仅要查询11:00-13:00,还要查询11:01-13:01和11:02-13:02等...

提前致谢。

sql sql-server
2个回答
1
投票
select t1.dt, count(*) as cnt 
from table t1 
join table t2 
  on t2.dt > t1.dt 
 and datediff(mi, t1.dt, t2.dt) < 120 
group by t1.dt 
having count(*) > 200

0
投票

我们可以使用CTEGROUP BYHAVING这个 -

declare @xyz table (id int identity(1,1),tpxID int,Rec_Creation_Date datetime)

insert into @xyz (tpxID, Rec_Creation_Date)
select 2995392, '2018-03-06 11:50:45.000' union all
select 2995391, '2018-03-06 11:39:48.000' union all
select 2995390, '2018-03-06 11:30:58.453' union all
select 2995389, '2018-03-06 11:30:49.297' union all
select 2995388, '2018-03-06 11:30:30.687' union all
select 2995387, '2018-03-06 11:30:22.547' union all
select 2995386, '2018-03-06 11:30:13.483' union all
select 2995385, '2018-03-06 11:30:04.813' union all
select 2995384, '2018-03-06 11:29:57.640' union all
select 2995383, '2018-03-06 11:29:49.670' union all
select 2995383, '2018-03-06 09:29:49.670'

;with cte as (
    select
        x.Rec_Creation_Date as StartDT,
        y.Rec_Creation_Date as EndDT
    from @xyz as x
    inner join @xyz as y on x.Rec_Creation_Date < y.Rec_Creation_Date
    where datediff(HOUR,x.Rec_Creation_Date, y.Rec_Creation_Date) >= 2
)
select
    cte.StartDT,
    cte.EndDT
from cte
inner join @xyz as x on x.Rec_Creation_Date between cte.StartDT and cte.EndDT
group by cte.StartDT , cte.EndDT
having count(*) > 200
order by cte.StartDT , cte.EndDT
© www.soinside.com 2019 - 2024. All rights reserved.