我为用户提供了以下操作序列,并为每个操作设置了DateTime
时间戳。
下面是一个示例表
Actions:
+------------+-------------+----------------------+
| session_id | action_name | time |
+------------+-------------+----------------------+
| 123abcd | ADD | 2014-08-27 13:41:02 |
+------------+-------------+----------------------+
| 123abcd | LIKE | 2014-08-27 13:43:02 |
+------------+-------------+----------------------+
| 123abcd | DELETE | 2014-08-27 13:45:02 |
+------------+-------------+----------------------+
| 123abcd | EMAIL | 2014-08-27 13:48:02 |
+------------+-------------+----------------------+
| 123abcd | LIKE | 2014-08-27 13:52:02 |
+------------+-------------+----------------------+
| 546erqr | ADD | 2014-08-27 14:02:02 |
+------------+-------------+----------------------+
| 546erqr | EMAIL | 2014-08-27 14:12:02 |
+------------+-------------+----------------------+
| 546erqr | LIKE | 2014-08-27 14:14:02 |
+------------+-------------+----------------------+
正如您所看到的,user
可以通过session
执行某些操作。
我对计算用户为每个会话发送电子邮件所花费的时间感兴趣。
基本上,我想要TIMESTAMPDIFF(SECOND, min(time), max(time))/60
直到action = EMAIL
。我尝试在SQL语句中使用where
子句执行它,但它没有工作。
对于输出,我想要类似的东西:
+------------+-----------------------+
| session_id | time_till_email_mins |
+------------+-----------------------+
| 123abcd | 7 |
+------------+-----------------------+
| 546erqr | 10 |
+------------+-----------------------+
一般来说,如果要做这样的计算(无论是时间差计算还是计算某些事情)直到某个动作,那么如何进行计算。
希望这是有道理的。如果您有任何问题,请告诉我
答案 0 :(得分:1)
您可以使用条件聚合执行此操作:
select session_id,
timestampdiff(second, min(case when action_name = 'EMAIL' then action_time end),
min(action_time)) / 60
from actions a
group by session_id;
答案 1 :(得分:1)
我想你可能想要这个:
select session_id,
min(time) as first_action_time,
min(case when action_name = 'EMAIL' then time end) as first_email_time,
timestampdiff(second,min(time),min(case when action_name = 'EMAIL' then time end)) as diff_in_secs
from actions
group by session_id
这是会话的第一个操作与操作名称为' EMAIL'的会话的第一个操作之间的秒数差异。
答案 2 :(得分:0)
使用子查询获取两个值。时间不是一个好的专栏名称。
select session_ID , **(datediff function using first_time and end_time)**
from
(select session_id , min(time) as first_time
from actions
group by session)a
inner join
(select session_id, time as end_time
from actions
where action_name = 'email'
group by session_ID) b
on a.session_id = b.session_id
不幸的是我不熟悉MySQL中的datediff / time diff函数(我把占位符放在选择行中),但你应该可以从这里开始工作。