假設我有一個包含一組數據點的表,每個數據點都包含一個時間戳和一個值。如果至少有N個連續記錄(按時間戳排序)高於給定值X,則我將如何編寫一個返回true的查詢(1),否則返回false(0)?超過閾值的值連續n分鐘
下做到這一點,連續3條記錄,但一般情況下無需建立一個動態查詢,並增加更多的不工作「和存在」的情況:
truncate table tblData
insert into tblData values ('1-jul-2013 13:01:00', 64)
insert into tblData values ('1-jul-2013 13:02:00', 13)
insert into tblData values ('1-jul-2013 13:03:00', 7)
insert into tblData values ('1-jul-2013 13:04:00', 17)
insert into tblData values ('1-jul-2013 13:05:00', 7)
insert into tblData values ('1-jul-2013 13:06:00', 18)
insert into tblData values ('1-jul-2013 13:07:00', 9)
insert into tblData values ('1-jul-2013 13:08:00', 20)
insert into tblData values ('1-jul-2013 13:09:00', 12)
insert into tblData values ('1-jul-2013 13:10:00', 21)
insert into tblData values ('1-jul-2013 13:11:00', 22)
insert into tblData values ('1-jul-2013 13:12:00', 3)
insert into tblData values ('1-jul-2013 13:13:00', 22)
insert into tblData values ('1-jul-2013 13:14:00', 20)
declare @x as int = 10
select count(*)
from tblData a
where a.dt in
(select dt from tblData b where b.value > @x and b.dt >= a.dt and b.dt < DATEADD(minute,1,a.dt)) and exists
(select dt from tblData b where b.value > @x and b.dt >= DATEADD(minute,1,a.dt) and b.dt < DATEADD(minute,2,a.dt)) and exists
(select dt from tblData b where b.value > @x and b.dt >= DATEADD(minute,2,a.dt) and b.dt < DATEADD(minute,3,a.dt))
想法?
是每個時間戳保證是對時間嗎? –