简体   繁体   English

给定时间间隔的SQL查询?

[英]SQL Query for a given time interval?

If I have this dataset below: 如果我在下面有这个数据集:

Timestamp   Clicks
1:40:11     5
2:40:13     10
3:42:56     20
4:42:23     30
7:45:59     23
9:45:34     24
10:47:23    24
12:47:12    24

So from the data above the minutes range go from 40-47 but skips 41 , 43 , 44 , and 46 in that range. 因此,从上面分钟的数据范围从去40-47但跳过414344 ,和46在该范围内。

I want to find the average number of clicks per minute in that range ( 40-47 ) and put a zero value for the minutes that are not within the range ( 41 , 43 , 44 , and 46 ). 我想找到每在该范围内(分钟点击的平均数40-47 ),并把一个零值不属于范围(内分414344 ,和46 )。

So the result should be like this: 所以结果应该是这样的:

Minute      Clicks
40          8
41          0
42          25
43          0
44          0
45          24
46          0
47          24

Any ideas on how to achieve something like this? 关于如何实现这样的想法?

You only need 60 series, so you can create a table with 60 rows which contains the 60 existing minutes: 您只需要60个系列,因此您可以创建一个包含60行的表,其中包含60分钟的存在时间:

[table serie]
minute
0
1
2
3
4
5
…

Then use left join to create simple query like this: 然后使用左连接创建简单的查询,如下所示:

select a.minute, IF(avg(b.Clicks),avg(b.Clicks),0) as avg_click from serie a
left join my_dataset b on a.`minute`*1 = SUBSTRING(b.Timestamp,-5,2)*1
group by minute

SUBSTRING(b.Timestamp,-5,2) will give you the minute from the end (to avoid wrong substring from the beginning if the HOUR has only 1 char). SUBSTRING(b.Timestamp,-5,2)将给您从末尾开始的分钟(如果HOUR只有1个字符,则避免从头开始输入错误的子字符串)。 We need to force comparison to INT by using *1 to CAST. 我们需要通过对CAST使用*1来强制与INT进行比较。

I would start with something like this 我将从这样的事情开始

    declare @StartTime DateTime = (select MIN(Timestamp) from tablename)
declare @EndTime DateTime = (select MAX(Timestamp) from tablename)
declare @CurrentMinute DateTime = @StartTime
declare @ResultTable (Minute int, Clicks int)


While @CurrentMinute <= @EndTime
begin
    insert into @ResultTable (Minute,Clicks)    
    select DatePart(Minute,@CurrentMinute) as Minute, (select isnull( Clicks  from tablename where DatePart(Minute,Timestamp) = DatePart(Minute,@CurrentMinute),0 )


end

select * from @ResultTable

this works by locating the lowest highest times and initializes the variable currentTime to the start time and continues in the while loop until the ending time it then insert into a temp row for every minute, if the results do not have a minute that matches it returns a null in the sub query and the is null insert a 0 for the clicks for that row as it had no row found 这将通过查找最短的最高时间并将变量currentTime初始化为开始时间,并在while循环中继续进行直到结束时间,然后每分钟将其插入到临时行中(如果结果没有与之匹配的分钟返回),从而开始工作子查询中为null,而null为该行的点击次数插入0,因为找不到行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM