首页 > 解决方案 > SQL 运行总秒数 - 时间戳/值

问题描述

我在编写一个每秒聚合我的结果的查询时遇到了麻烦。在这里,我正在创建一个示例表并进行两次插入。

create table example (
  start timestamp,
  stop timestamp,
  qty INTEGER
);

insert into example(start, stop, qty)
values ('2019-06-11 09:59:59', '2019-06-11 10:00:04', 14);
insert into example(start, stop, qty)
values ('2019-06-11 10:00:00', '2019-06-11 10:00:03', 12);

我需要一个查询,它会返回如下内容:
在此处输入图像描述

或者 在此处输入图像描述

其中 1,2,3,4,5 是前 2 次插入的秒数。09:59:59 到 10:00:04 有 5 秒。

和 14, 26, 26, 26, 14 是相同日期的行的数量之和。14 + 12 = 26 因此这个数字。而且这种加法只发生在同一时刻发生的几秒钟内。

这样的查询可能吗?

标签: sql

解决方案


您可以很容易地获得边界:

with ss as (
      select start as ts, qty
      from t
      union all
      select stop, -qty
      from t
     ) 
select ts, sum(qty) as day_qty,
       sum(sum(qty)) over (order by ts) as running_qty
from ss
group by ts;

当某事开始或停止时,这具有所有时间戳。它不会“填充”值。最好的方法取决于数据库。


推荐阅读