Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
SQL - Find series of timestamps with small gaps
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
create table T ([timestamp] datetime); insert into T ([timestamp]) values ('2015-07-15 15:01:21'), ('2015-07-15 15:17:44'), ('2015-07-15 15:17:53'), ('2015-07-15 15:18:34'), ('2015-07-15 15:21:41'), ('2015-07-15 15:58:12'), ('2015-07-15 15:59:12'), ('2015-07-15 16:05:12'), ('2015-07-15 17:02:12'); select 'Version 1' as "Query"; with Boundaries as ( select "timestamp" as Stamp, coalesce( case when datediff(second, prev_timestamp, "timestamp") >= 1800 then 1 else 0 end, 1 ) as IsBoundary from T t cross apply ( select max(t2."timestamp") as prev_timestamp from T t2 where t2."timestamp" < t."timestamp" ) as n ), Blocks as ( select Stamp, sum(IsBoundary) over (order by Stamp) as BlockNum from Boundaries ) select min(Stamp) as "from", max(Stamp) as "to" from Blocks group by BlockNum; select 'Version 2' as "Query"; with Boundaries as ( select "timestamp" as Stamp, coalesce( case when datediff(second, prev_timestamp, "timestamp") >= 1800 then 1 else 0 end, 1 ) as IsBoundary from T t cross apply ( select max(t2."timestamp") as prev_timestamp from T t2 where t2."timestamp" < t."timestamp" ) as n ), Blocks as ( select Stamp, (select sum(b2.IsBoundary) from Boundaries b2 where b2.Stamp <= b.Stamp) as BlockNum from Boundaries b ) select min(Stamp) as "from", max(Stamp) as "to" from Blocks group by BlockNum;
View schema
Execution time: 0,06 sec, rows selected: 8, rows affected: 9, absolute service time: 0,31 sec
edit mode
|
history
|
discussion
Query
1
Version 1
from
to
1
15.07.2015 15:01:21
15.07.2015 15:21:41
2
15.07.2015 15:58:12
15.07.2015 16:05:12
3
15.07.2015 17:02:12
15.07.2015 17:02:12
Query
1
Version 2
from
to
1
15.07.2015 15:01:21
15.07.2015 15:21:41
2
15.07.2015 15:58:12
15.07.2015 16:05:12
3
15.07.2015 17:02:12
15.07.2015 17:02:12