gpt4 book ai didi

sql - 查找时间序列的运行总和高于给定阈值的位置

转载 作者:行者123 更新时间:2023-12-02 06:54:21 27 4
gpt4 key购买 nike

我有一些时间序列数据。例如,查看以下值(假设此处的时间为分钟):

User Time Value
a 0 10
b 1 100
c 2 200
a 3 5
e 4 7
a 5 999
a 6 8
b 7 10
a 8 10
a 9 10
a 10 10
a 11 10
a 12 100

现在我想知道在任何给定的 5 分钟间隔内,总和是否达到了 1000 以上。

例如,在上面的示例中,我应该得到诸如用户 a,第 5、6、8、9 分钟的输出。

最佳答案

这对于窗口函数来说是一项简单的任务:

select *
from
(
select t.*
,sum("Value") -- cumulative sum over the previous five minutes
over (partition by "user"
order by "Time"
range 4 preceding) as sum_5_minutes
from Table1 t
) dt
where sum_5_minutes > 1000

参见 fiddle

编辑:SQLFiddle 又下线了,不过你还可以搜索接下来的 5 分钟。

Edit2:SQLFiddle 离线,但如果数据类型是 TimeStampDate,则必须使用间隔而不是整数:

select *
from
(
select t.*
,sum("Value")
over (partition by "User"
order by "Time"
range interval '4' minute preceding) as sum_prev5_minutes
,sum("Value")
over (partition by "User"
order by "Time"
range between interval '0' minute preceding -- or "current row" if there are no duplicate timestamps
and interval '4' minute following) as sum_next5_minutes

from Table1 t
) dt
where sum_prev5_minutes > 1000
or sum_next5_minutes > 1000

关于sql - 查找时间序列的运行总和高于给定阈值的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34815315/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com