针对某列,希望该列的值变化时,返回变化相应的两条记录,SQL如何实现?

比如:0 0 0 0 1 1 1 0 0 表示一列,想要返回0 1 1 0 以及时间等其它字段。

请先 登录 后评论

2 个回答

Juntao Wang

示例代码如下:

t = table(0 0 0 1 1 1 0 0 as value, 2022.01.01 12:00:00 + 1..8 as time, take(1, 8) as id)
select * from t where id = 1, (value != prev(value) and isValid(prev(value))) or (value != next(value) and isValid(next(value))) context by id
请先 登录 后评论
Yating Xie

如果需要按分组实现的话,建议用context by和having,示例代码如下:

t = table(0 0 0 1 1 1 0 0 1 1  0 0 1 2 as value, 2022.01.01 12:00:00 + 1..14 as time, take(1, 8) join take(2, 6) as id)
select * from t context by id having  (value != prev(value) and isValid(prev(value))) or (value != next(value) and isValid(next(value))) 

关于context by用法的说明:

context by和having组合使用时,先进行context分组然后在组内计算having的逻辑;

若是楼上where和context by的写法,会先对全部数据进行where判断再分组。

请先 登录 后评论