sql计算跳出率

bcs8qyzn  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(339)

我有以下sql表(postgres):

+-----------+------------+-------+
| SessionID |  Received  | Event |
+-----------+------------+-------+
|         1 | 1595207019 | visit |
|         1 | 1595207020 | play  |
|         2 | 1595207040 | visit |
|         1 | 1595207050 | click |
+-----------+------------+-------+

我想计算bounce rate,其中bounce被定义为visit event,后面没有任何其他具有相同会话id的事件。

ogsagwnx

ogsagwnx1#

您可以像这样显式查询“反弹”的数量:

select count(*)
from t as t1
where t1.event = 'visit'
  and not exists (select * from t as t2 where t1.received < t2.received and t1.sessionid = t2.sessionid)

不确定“反弹率”的分母具体是什么?每次反弹?#反弹/#事件?

g52tjvyc

g52tjvyc2#

嗯。我想你应该总结一下 session_id 并计算访问的类型。然后聚合。你的问题不是100%清楚,但我认为:

select (count(*) filter (where num_notvisits = 0) * 1.0 / count(*)) as bounce_rate
from (select session_id,
             count(*) filter (where event = 'visit') as num_visits,
             count(*) filter (where event <> 'visit') as num_notvisits
      from t
      group by session_id
     ) s
where num_visits > 0;

这是访问和非访问事件的会话数除以访问会话数的比率。
实际上,您可以将“外部选择”更简单地表述为:

select avg( (num_notvisits = 0)::int ) as bounce_rate

相关问题