SQL 如何根据当前事件和下一个事件确定操作的持续时间?

标签 sql postgresql

我有一个包含两列的表格:操作开始时间和操作名称。

<表类=“s-表”> <标题> 时间 Action <正文> 2023-07-27 04:52:00.000 正在运行 2023-07-27 04:55:00.000 步行 2023-07-27 04:59:00.000 步行 2023-07-27 05:01:00.000 坐着 2023-07-27 05:06:00.000 步行 2023-07-27 05:10:00.000 正在运行

我需要知道操作的持续时间:开始和结束时间。开始时间是操作的时间,该时间是已知的。
但如何知道结束时间呢?即下一个 Action 的开始与当前 Action 不同?

“行走” Action 示例

<表类=“s-表”> <标题> 时间开始 time_end <正文> 2023-07-27 04:55:00.000 2023-07-27 05:01:00.000 2023-07-27 05:06:00.000 2023-07-27 05:10:00.000

最佳答案

请参阅下面的更正版本。这假设每个操作都是唯一的。

I think you could use the lag function to achieve your goal.

select 
    action,
    time as time_start,
    lag(time, -1) over(order by time) as time_end
from <table_name>

In this case the time_end for the last row will be equal to NULL, which I think is correct, as it isn't known yet.

编辑:在 @Tim Biegeleisen 发表评论之后,这是基于他的工作的更新答案。但是,它可以正确找到相同连续操作组的 time_end 值。

WITH data AS (
    SELECT '2023-07-27 04:52:00.000' AS time, 'running' AS action UNION ALL
    SELECT '2023-07-27 04:53:00.000', 'running' UNION ALL
    SELECT '2023-07-27 04:55:00.000', 'walking' UNION ALL
    SELECT '2023-07-27 04:59:00.000', 'walking' UNION ALL
    SELECT '2023-07-27 05:01:00.000', 'sitting' UNION ALL
    SELECT '2023-07-27 05:06:00.000', 'walking' UNION ALL
    SELECT '2023-07-27 05:10:00.000', 'walking' UNION ALL
    SELECT '2023-07-27 05:12:00.000', 'walking' UNION ALL
    SELECT '2023-07-27 05:15:00.000', 'walking' UNION ALL
    SELECT '2023-07-27 05:20:00.000', 'running' 
),
withLag AS (
    SELECT 
        action,
        time AS start_time,
        LAG(time) OVER (ORDER BY time desc) AS next_time,
        ROW_NUMBER() OVER (ORDER BY time) AS row_num,
        ROW_NUMBER() OVER (PARTITION BY action ORDER BY time) AS group_num
    FROM data
)
SELECT action, min(start_time) as time_start, max(next_time) as time_end
FROM withLag
GROUP BY action, row_num - group_num
order by time_start

最终我们达到了预期的结果:

enter image description here

关于SQL 如何根据当前事件和下一个事件确定操作的持续时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76778105/

相关文章:

mysql - 产品 alpha-num 序列号的数学运算 |数据库设计

python - Django 2 + PostgreSQL FullText 搜索不匹配它应该的

postgresql - Postgres 时差

postgresql - 从 PostgreSQL 中删除未命名的约束

SQL - 时间序列 - 对于缺失值返回 0

SQL 数组聚合和连接

python - 1241, 'Operand should contain 1 column(s)' Pandas to_sql

sql - 根据计数连接 3 个表

ruby-on-rails - 如何在事件记录中编写子查询?

sql - Rails Activerecord 关系 : using subquery as a table for a SQL select statement