计算会话中两个操作之间的时间

时间:2016-04-28 13:34:45

标签: sql google-bigquery

我有以下表结构

$data1 = $this->input->post('forwards');
$data2 = $this->input->post('defenders');

.....manipulation, then insert into table

我正在尝试在两个事件之间获得时间,在这个特殊情况下,我想知道在一个会话中FIRST视图和FIRST购买事件之间已经过了多少时间。

如何在GROUP BY中为数据应用WHERE?基本上我想通过sesssionID进行分组,只获得包含查看和购买操作的会话,我希望在单个会话中获得FIRST视图和FIRST购买事件之间的时间。

我如何达到要求的结果?

谢谢

3 个答案:

答案 0 :(得分:2)

相当常见的sql语法,希望google-bigquery支持

select sessionId, 
  min(case event when 'view' then created_on end) as firstView,
  min(case event when 'buy' then created_on end) as firstBuy
from t
where event in ('view', 'buy')
group by sessionId
having max(event) != min(event)

答案 1 :(得分:2)

如果您想避免额外的加入 - 请尝试以下

SELECT 
  sessionId, 
  TIMESTAMP_TO_SEC(firstBuy) - TIMESTAMP_TO_SEC(firstView) AS sec_to_buy
FROM (
  SELECT sessionId, 
    MIN(CASE WHEN event = 'view' THEN created_on END) AS firstView,
    MIN(CASE WHEN event = 'buy' THEN created_on END) AS firstBuy
  FROM (
    SELECT * FROM 
      (SELECT 1 AS sessionId, 'view' AS event, TIMESTAMP('2016-01-01 12:24:01') AS created_on),
      (SELECT 1 AS sessionId, 'buy' AS event,  TIMESTAMP('2016-01-01 12:25:05') AS created_on),
      (SELECT 2 AS sessionId, 'view' AS event, TIMESTAMP('2016-01-01 12:25:09') AS created_on),
      (SELECT 1 AS sessionId, 'view' AS event, TIMESTAMP('2016-01-01 12:27:10') AS created_on),
  )
  GROUP BY sessionId
  HAVING firstView <= firstBuy
)

答案 2 :(得分:1)

一个简单的解决方案可能是: 获取每个sessionID的最小created_at,其中查看事件并使用在每个sessionID创建的最小值来加入它,其中事件为buy。使用内部联接只包含两个记录...

  

中选择A.sessionID,A.firstView,B.firstBuy,datedif(依赖于rdbms )      

(从tblName中选择sessionID,min(created_on)作为firstView,其中event ='view'group by sessionID)A

     

内部联接

     

(选择sessionID,min(created_on)作为firstBuy from tblName where event ='buy'group by sessionID)B

     

在A.sessionID = B.sessionID