sql - 两个事件之间的时间

标签 sql postgresql

如果有一个表来跟踪用户的某些事件。

 id | user_id | action |         created_at         
----+---------+--------+----------------------------
  5 |       1 | create | 2016-09-08 11:29:56.325691
  6 |       1 | clear  | 2016-09-08 11:30:00.08604
  7 |       2 | create | 2016-09-08 11:30:10.12857
  8 |       2 | clear  | 2016-09-08 11:30:14.238685
  9 |       3 | create | 2016-09-08 11:30:42.192843

总是有一个 create 操作,后面可能有一个 clear 操作。

CREATE TYPE user_actions AS ENUM ('create', 'clear');

现在我想查询这两个 Action 的时间差,得到用户的createclear之间的time_diff。

现在您可以假设 user 没有多个条目(例如,至少一个 create 和 maximal 另一个 clear)。

我想要这样的结果:

 user_id |    time_diff    
---------+-----------------
       1 | 00:00:03.760349
       2 | 00:00:04.110115

最佳答案

您可以使用以下查询:

SELECT user_id,
       MAX(CASE WHEN action = 'clear' THEN created_at END) -
       MAX(CASE WHEN action = 'create' THEN created_at END) AS time_diff 
FROM mytable
GROUP BY user_id 
HAVING COUNT(*) = 2

HAVING 子句过滤掉仅包含 create 操作的 user_id 组,例如带有 id=9 的记录在OP中。

Demo here

关于sql - 两个事件之间的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39387712/

相关文章:

mysql - 在 SQL 中计算结果的最佳方法在哪里?

sql - Postgresql在ubuntu中更改数据目录

mysql - SQL 查询从同一列中选择多个值

mysql - 如何在 MYSQL 中更新/使 View 可更新

sql - MYSQL 查询 DATEDIFF() 函数出错

ruby-on-rails - 如何使用 postgres 和 ActiveRecord 检索所有重复的电子邮件

python - psycopg2 操作错误 : cursor does not exist

postgresql - 使用 PPGool-ii 在 Amazon EC2 上部署高可用性 Postresql 9.0

SQL Server 生成脚本以使用其他数据库中的数据填充表?

sql - 创建链接到另外 2 个表的表的聚合查询