我的数据以5分钟的包裹发送给我。我正在逐秒读取设备的状态,并且已经使用pandas构建了一个脚本来聚合相同状态的连续行。我的数据看起来像这样。
timestamp status length
00:00:00 1 38
00:00:38 0 72
00:01:50 1 27
...
我希望查询一整天的5分钟包,没有5分钟包的边缘是明显的。目前,当我在AWS Athena中查询多个数据包时,我发现相同状态的连续行未聚合。
EG
timestamp status length
00:04:02 1 24
00:04:26 0 15
00:04:41 1 19
00:05:00 1 11
00:05:11 0 8
00:05:19 1 22
...
我想聚合这两行,以便使用标准SQL将5分钟包边缘的状态聚合在一起,这样上面的示例如下所示。具有相等状态位的连续行被聚合为一个,这些连续条目的长度相加。
timestamp status length
00:04:02 1 24
00:04:26 0 15
00:04:41 1 30
00:05:11 0 8
00:05:19 1 22
...
SQL中是否有能力按照上述结构返回此查询?
这是一个“差距和岛屿”问题。亚马逊Athena支持row_number()
,因此您可以使用行号方法的不同来解决它:
select status, min(timestamp) as timestamp, sum(length) as length
from (select t.*,
row_number() over (order by timestamp) as seqnum,
row_number() over (partition by status order by timestamp) as seqnum_s
from t
) t
group by status, (seqnum - seqnum_s);