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
以上数据显示了一段时间内车辆的速度,鉴于以上数据我需要达到以下结果:
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
下面的代码几乎就在那里,但在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
我想我一直盯着这个太久了。我尝试过使用相关子查询进行自联接,但是我觉得我错过了一些明显的东西?这是针对2008项目的,因此不必使用之前的任何版本。任何帮助将不胜感激。
答案 0 :(得分:1)
你走了!你基本上错过了你需要检查最新加速度的部分,只要它没有加速(我的查询中不存在的部分更多)
create table #t (recordno int, speed int)
insert into #t
select 1, 0
union select 2, 0
union select 3, 0
union select 4, 0
union select 5, 23
union select 6, 66
union select 7, 48
union select 8, 0
union select 9, 31
union select 10, 0
union select 11, 34
union select 12, 23
;with acc as (
select
t1.*,
case when t1.speed >= isnull(t2.speed, 0) then t1.speed else -1 end as 'accel'
from
#t t1
left join #t t2
on t1.recordno = t2.recordno + 1
)
select
a.recordno, a.speed,
case
when a.accel >= 0 then a.accel
else (
select accel
from acc a1
where a1.recordno < a.recordno and a1.accel >= 0
and not exists (
select 1
from acc a2
where a2.recordno < a.recordno and a2.accel >= 0 and a2.recordno > a1.recordno)
)
end
from
acc a
drop table #t
答案 1 :(得分:1)
你可以这样做:
declare @t table(recordno int, speed int)
insert into @t select 1, 0
union select 2, 0
union select 3, 0
union select 4, 0
union select 5, 23
union select 6, 66
union select 7, 48
union select 8, 0
union select 9, 31
union select 10, 0
union select 11, 34
union select 12, 23
;with a as
(
select recordno, speed, 0 LastAcceleration from @t
where recordno = 1
union all
select b.recordno, b.speed,
case when b.speed > LastAcceleration then b.speed else
case when a.speed = 0 then b.speed else LastAcceleration end end
from a join @t b on b.recordno - 1 = a.recordno
)
select recordno, speed, LastAcceleration from a
option (maxrecursion 0)