这个sql怎么写?

这个sql怎么写?

test表,有time,num,type  3个字段,表的数据类似是这样

time          num    type
时间1      1        A
时间2      1    A
时间3      1   A
时间4      1   B
时间5      1   B
时间6              1   B
时间7 1   B

时间8 2   C
时间9 2   C
时间10 2   C
时间11 2   C
时间12 2   D
时间13   2   D
时间14 2   D

以上数据时间是倒序排列的,即时间1最新,时间14最老,

现在要把同一个num的type发生改变时的前后2条记录查出来,
即对应上面的:

时间3 1   A
时间4 1   B
时间11 2   C
时间12 2   D

查出这4条记录,sql应该怎么写? 数据库是Oracle。

 

[code="sql"]
select time,num,type from (
select
time,num,type,
lag(type) over(partition by num order by time desc) lag_type,
lead(type) over(partition by num order by time desc) lead_type
from t
) a
where a.lag_type is not null
and a.lead_type is not null
and (a.type <> a.lag_type or a.type <> a.lead_type)
[/code]