sql查询以特定的时间间隔选择记录?

polhcujo  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(371)

我有以下数据:

X,        Y,        Receiver, Timestamp 
1.534268, 51.03796, 126,      2017-06-01 02:01:01 
1.534268, 51.03793, 126,      2017-06-01 02:03:01 
1.534268, 51.03799, 133,      2017-06-01 02:05:01 
1.534268, 51.03716, 133,      2017-06-01 02:09:01 
1.534268, 51.03766, 126,      2017-06-01 02:10:01 
1.534268, 51.03766, 126,      2017-06-01 02:17:01 
1.534268, 51.03795, 126,      2017-06-01 02:19:01 
1.534268, 51.03791, 133,      2017-06-01 02:22:01 
1.534268, 51.03746, 126,      2017-06-01 02:24:01 
1.534268, 51.03796, 133,      2017-06-01 02:31:01

我需要sql查询来完成两件事:
以大约10分钟的间隔选择记录,因此我最终得到如下结果:

X,        Y,        Receiver, Timestamp 
1.534268, 51.03796, 126,      2017-06-01 02:01:01 
1.534268, 51.03766, 126,      2017-06-01 02:10:01 
1.534268, 51.03795, 126,      2017-06-01 02:19:01 
1.534268, 51.03796, 133,      2017-06-01 02:31:01

然后,我将如何修改查询以15分钟、30分钟和每小时的间隔选择数据?
从上面的结果,我如何得到一个计数记录的数量,落在每个接收器,即。

Receiver 126: 3,
Receiver 133: 1
mspsb9vt

mspsb9vt1#

“像这样的东西”。嗯,最简单的方法是每十分钟从“日历时钟”中取出第一张唱片。这将是00:00、00:10、00:20等之后的第一个记录。
为此,您可以使用 first_value() 以及 select distinct :

select distinct
       first_value(x) over (partition by dd, hh, mm order by timestamp) as x,
       first_value(y) over (partition by dd, hh, mm order by timestamp) as y,
       first_value(receiver) over (partition by dd, hh, mm order by timestamp) as receiver,
       min(timestamp) over (partition by dd, hh, mm),
       count(*) over (partition by dd, hh, mm) as cnt

from t cross apply
     (values (convert(date, timestamp), datepart(hour, timestamp), datepart(minute, timestamp) / 6)
     ) v(dd, hh, mm);

这并不完全返回您指定的结果,但它似乎满足问题中提到的条件。
编辑:
我突然想到,从第一个时间戳开始,你可能需要10分钟的间隔。如果是:

select (case when seqnum = 1 then x end) as x,
       (case when seqnum = 1 then y end) as y,
       (case when seqnum = 1 then receiver end) as receiver,
       min(timestamp),
       count(*)
from (select t.*,
             datediff(second, min_ts, timestamp) / (10 * 60) as grp,
             row_number() over (partition by datediff(second, min_ts, timestamp) / (10 * 60) order by timestamp) as seqnum,
      from (select t.*,
                   min(timestamp) over () as min_ts
            from t
           ) t
     ) t
group by grp;

我认为这会返回您指定的组。按grp分组;

uurv41yg

uurv41yg2#

使用下面的查询,
结果1:

select t1.* from table t1
inner join t2
on (datediff(minute, starttime, endtime) = 10);

结果2:

select x, t, reciever, count(1)
from
(select t1.* from table t1
inner join t2
on (datediff(minute, starttime, endtime) = 10)) qry
group by x, t, reciever;

相关问题