RecordNo Speed
-------- -----
1 0
2 0
3 0
4 0
5 23
6 66
7 48
8 0
9 31
10 0
11 34
12 23
The above data shows the speed of vehicle over a time period, given the above data I need to achieve the result below:
RecordNo Speed LastAcceleration
-------- ----- ----------------
1 0 0
2 0 0
3 0 0
4 0 0
5 23 23
6 66 66
7 48 66
8 0 66
9 31 31
10 0 31
11 34 34
12 23 34
The code below is almost there but falls over on Recordno 8:
select
curr.recordno,curr.speed
,CASE WHEN curr.speed >= ISNULL(prev.speed,0) THEN curr.speed
ELSE (
SELECT MAX(speed) FROM speedtest
WHERE recordno between (CASE WHEN curr.speed >= prev.speed then curr.recordindex else prev.recordno end ) and curr.recordno
)
END as LastAcceleration
From speedtest prev RIGHT JOIN speedtest curr
on prev.vrm = curr.vrm
and prev.recordno+1 = curr.recordno
order by curr.recordno
I think I’ve been staring at this one too long. I’ve tried self-joins with correlated sub-queries but think I’m missing something obvious? This is for a 2008 project so doesn’t have to work with any versions prior to that. Any help would be appreciated.
Here you go! You basically missed the part where you need to check for the latest acceleration whenever its not accelerating (the not exists portion of my query moreorless)