sql - 如何根据postgres中的按列分组的某些条件获取最后一行

标签 sql postgresql

我有一张 table

task_id     timestamp                           event_type
1           "2018-12-20 14:43:53.661153+01"     "open"
1           "2018-12-20 14:43:53.661153+01"     "interrupted"
1           "2018-12-20 14:43:53.661153+01"     "opened"
1           "2018-12-20 14:44:53.661153+01"     "closed"
2           "2018-12-20 14:43:53.661153+01"     "opened"
2           "2018-12-20 14:43:53.661153+01"     "interrupted"
2           "2018-12-20 14:43:53.661153+01"     "opened"
3           "2018-12-20 14:43:53.661153+01"     "opened"
3           "2018-12-20 14:45:53.661153+01"     "closed"

我只需要获取 event_type 关闭的任务的数据,这是该 task_id 的最后一行。 在上面的示例中,我应该获取 task_id 1 和 3 的数据,但不能获取 2 的数据,因为任务 2 尚未关闭。 因此,对于每个任务,如果最后一行关闭,那么它应该获得该任务的最后一行和倒数第二行之间的时间差。

task_id     time_diff_minutes
1           1
3           2

最佳答案

您可以利用postgres LAG功能。检查下面的 SQL :-

select test_id, extract(epoch from(event_time - prev_time))/60 as diff
from (select test_id,
LAG(event_time) over(partition by test_id) prev_time
,event_time
,event_type
from test
) a11
where event_type = 'closed'

SQL Fiddle

关于sql - 如何根据postgres中的按列分组的某些条件获取最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54004408/

相关文章:

php - 在 Ubuntu10 中安装 pdo_pgsql 不工作

VBA、ADO.Connection 和 PostgreSQL 如何将查询参数传递给 pg_typeof()

mysqli - 如何在没有 PHP 的情况下计算插入之前的行数?

sql - 公共(public)架构未在安全定义器函数的搜索路径中定义,但仍可访问

php - 按天从mysql数据库中获取查询

sql - 来自带有子级别的 SQL 查询的 JSON

mysql - 如何在sql中选择前一个最接近的值

sql - postgres : schema does not exist when creating a table

javascript - 按日期升序索引,但最后显示过去的日期

postgresql - postgres SQL 状态 : 22P02