user5228393
user5228393

Reputation:

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.

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).

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?

Upvotes: 2

Views: 412

Answers (2)

4givN
4givN

Reputation: 3234

You only need 60 series, so you can create a table with 60 rows which contains the 60 existing minutes:

[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). We need to force comparison to INT by using *1 to CAST.

Upvotes: 1

Jon Cluff
Jon Cluff

Reputation: 109

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

Upvotes: 0

Related Questions