【问题标题】:SQL calculate bounce rateSQL计算跳出率
【发布时间】:2020-07-20 01:15:10
【问题描述】:

我有以下 SQL 表(Postgres):

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

我想计算跳出率,其中 bounce 被定义为访问事件之后没有任何其他具有相同会话 ID 的事件。

【问题讨论】:

  • 如果一个会话中有多次访问怎么办?如果会话没有访问怎么办?
  • 一个会话中不可能有多个“访问”事件,访问本质上是会话创建事件。出于同样的原因,如果没有“访问”事件,会话就无法存在。实际上在我的应用程序中,事件甚至被称为“session_start”,我想为这个问题简化它:)

标签: sql postgresql


【解决方案1】:

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

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)

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

【讨论】:

  • 分母应该是会话总数。所以跳出率决定了只有访问事件而没有其他事件的会话百分比(用户登陆页面,因此创建了一个会话,但没有做任何其他事情)。
  • @StefanD 。 . .我看不出这是如何计算“率”的,因此不认为它回答了您提出的问题。
  • @GordonLinoff 你是对的,它没有完全回答问题,但揭示了关键部分。完整的解决方案可能是:SELECT(select 100.0*count(*) from t as t1 where t1.event = 'visit' and not exists (select * from t as t2 where t1.received
  • @StefanD 。 . .只是注意到我在实际回答问题时遇到了麻烦。
  • @GordonLinoff 不确定您的建议是什么...
【解决方案2】:

嗯。 . .我想您想通过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

【讨论】:

    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多