Just something interesting come in my mind. Assume that we have a table (in SQL Server) like this:
- Location
- Velocity
- Time
for example:
Location Velocity Time
1 40 1:20
2 35 2:00
3 45 2:05
4 50 2:30
5 60 2:45
6 48 2:55
7 40 3:00
8 35 3:15
9 50 3:20
10 70 3:30
11 50 3:35
12 40 3:40
Assume that speed barrier is 40kph, the output is something like this
Starttime Endtime
2:05 3:00
3:20 3:35
What is the best way to determine over speed periods (speed barrier is defined) ? My first idea was loading the table into an array, and then iterate over array to find these periods:
(Pseudo C# code)
bool isOverSpeed = false;
for (int i =0;i<arr.Length;i++)
{
if (!isOverSpeed)
if (arr[i].Velocity > speedBarrier)
{
#insert the first record into another array.
isOverSpeed = true;
}
if(isOverSpeed)
if (arr[i].Velocity < speedBarrier)
{
#insert the record into that array
isOverSpeed = false;
}
}
It works, but somewhat “not very effectively”. Is there a “smarter” way, such as a T-SQL query or another algorithm to do this?
You can achieve this by using CTE (Common Table Expressions).
The query below works against the Adventure Works demo table of SQL Server (the “speed limit” being 7).
This is strongly inspired by another question on SO: GROUP BY for continuous rows in SQL.
Something along these lines should suit you: