sql - 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 因此这个数字。而且这种加法只发生在同一时刻发生的几秒钟内。
这样的查询可能吗?
解决方案
您可以很容易地获得边界:
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;
当某事开始或停止时,这具有所有时间戳。它不会“填充”值。最好的方法取决于数据库。
推荐阅读
- python - 正则表达式提取键组之间所有可能的字符组合
- reactjs - 在反应中将文本垂直对齐到底部
- angular - 在 Angular 9 中,如何在父组件通过 Observable 加载数据后重新加载子组件?
- mysql - Spring JPA + Mysql,如何实现一个SELECT、FROM、WHERE查询?
- sql - 指向主键的外键,该主键也是唯一键的一部分
- r - R中的自动模型可视化
- python - Djago 模板卡对齐 [Django 2.2]
- amazon-web-services - Amazon MSK 中的 zookeeper 节点是否位于不同的可用区?
- java - 调度程序是否会在每次使用时创建固定数量的工作人员?
- jms - io.netty.util.ThreadDeathWatcher$Entry 占用堆导致OOM