我想给重复的recods提供序列编号并计算时间延迟而不能这样做
示例:
id time
A 12h30
A 13h45
A 19h48
B 8h00
B 10h12
C 22h50
D 9h02
D 16h46
预期查询结果
id time sequence lag
A 12h30 1 0h00
A 13h45 2 1h15
A 19h48 3 6h02
B 8h00 1 0h00
B 10h12 2 2h12
C 22h50 1 0h00
D 9h02 1 0h00
D 16h46 2 6h44
我所能做的就是用这个查询重新编号一个连续的序列
SELECT count(*)as rank, a1.id
FROM table a1, table a2
where a1.id >=a2.id
group by a1
order by rank, a1.id
最好的做法是什么?
非常感谢
答案 0 :(得分:2)
您可以使用row_number()
作为序列,lag()
计算前一行之间的时差
select
id,
time,
row_number() over(partition by id order by time) sequence,
(case when (lag(id) over (order by id, time)) = id
then time - (lag(time) over (order by id, time))
else 0
end) diff
from mytable t1
order by id, time
您可能必须根据time
列的类型修改case语句。