1

您好,有以下数据:

KEY                 VALUE               TIMESTAMP
-------------- ---------- -----------------------
0F8CE962              900          20141124054503
0F8CE962              900          20141124082431
0F8CE962                0          20141124083808
0F8CE962                0          20141124104408
0F8CE962                0          20141124105009
0F8CE962                0          20141124110213
0F8CE962              900          20141124110720
0F8CE962              900          20141125051641
0F8CE962                0          20141125054112

除了最后两行之外,每一行都与接下来的大约 15 分钟“相距”。如果我执行:

select KEY, sum(VALUE), min(TIMESTAMP), max(TIMESTAMP)
from myTable
group by KEY

我得到(当然)

KEY            sum(VALUE)         min(TIMESTAMP)          max(TIMESTAMP)
-------------- ---------- ----------------------- -----------------------
0F8CE962             3600          20141124054503          20141125054112

我需要的是只聚合不同的行,一旦订购,最多 15 分钟。这就是我想要的:

select KEY, sum(VALUE), min(TIMESTAMP), max(TIMESTAMP)
from myTable
group by KEY
some_magic_function(max(15 minutes))

KEY            sum(VALUE)         min(TIMESTAMP)          max(TIMESTAMP)
-------------- ---------- ----------------------- -----------------------
0F8CE962             2700          20141124054503          20141124110720
0F8CE962              900          20141125051641          20141125054112

可能吗?

4

1 回答 1

1

您可以使用其他地方演示的“组开始”方法。应用于您的示例并假设时间戳是或可以转换为数值:

with mytable1 as
  (select mytable.*
        , case
            when lag(timestamp, 1, timestamp-150001) over
                   (partition by key order by timestamp) < timestamp-150000
            then 1
            else 0
          end start_of_group
    from mytable)
, mytable2 as
  (select mytable1.*
        , sum(start_of_group) over (partition by key order by timestamp) grp
   from  mytable1)
select key
     , sum(value)
     , min(timestamp)
     , max(timestamp)
from mytable2
group by key
       , grp
order by key
       , min(timestamp)
于 2014-12-04T15:56:24.593 回答