计算跳出率SQL Server 2008

时间:2016-08-04 13:12:24

标签: sql-server sql-server-2008 tsql

我正在尝试使用Sharepoint的审核数据计算SQL Server中页面的跳出率。

ItemId  UserId  DocLocation  Occurred
1       1       Home.aspx    2016-08-02 13:39:41
1       2       Home.aspx    2016-08-02 13:40:07
2       1       Other.aspx   2016-08-02 13:40:16
3       1       Items.aspx   2016-08-02 13:40:17
2       2       Other.aspx   2016-08-02 13:40:11

ItemId是页面的ID,DocLocation页面的位置,当用户进入页面时Occurred

要计算跳出率,我们必须将跳出次数除以总次数。

当用户在不到5秒的时间内离开页面时就会发生跳出。

这应该是该表的结果:

ItemId  Bounces  Visits  BounceRate(Bounces/Visits)
1       1        2       0.5
2       1        2       0.5
3       0        1       0

我想计算一个弹跳,计算自用户执行检查以来用户访问另一个页面的次数。如果该时间少于5秒,则将其视为反弹。

我正在创建一个执行查询的存储过程来显示每个页面的跳出率,但这不起作用。

SELECT
    SUM(CASE 
           WHEN (DATEDIFF(second, @Occurred, 
                                 (SELECT TOP 1 a.Occurred
                                  FROM [AuditPages] a
                                  WHERE a.UserId = @userId 
                                    AND a.Occurred > @occurred
                                  ORDER BY a.Occurred ASC))) < 30 
              THEN 1.0
              ELSE 0.0 
        END) / COUNT(@itemId)

有人知道我如何计算这个跳出率?

感谢所有答案。

2 个答案:

答案 0 :(得分:1)

我喜欢将row_number用于此类排序问题。下面的查询给出了期望的结果。我发现CTE的性能有时会因较大的表而出现问题,您可能需要转换为临时表。如果您有可能希望在将来使用4.5秒或更长时间,可以考虑使用毫秒。

declare @bounce_seconds int = 5;

with audit_cte as (

    select  *, ROW_NUMBER() over (partition by UserId order by Occurred) row_num
    from    AuditPages
    --order by UserId,row_num
)
select      a.ItemId, sum(a.bounce) Bounces, count(1) Visits, sum(a.bounce)/convert(float, count(1)) BounceRate
from        (
            select      a1.ItemId, datediff(s,a1.Occurred, a2.Occurred) elapsed, case when datediff(s,a1.Occurred, a2.Occurred) < @bounce_seconds then 1 else 0 end bounce
            from        audit_cte a1
            left join   audit_cte a2
                        on  a2.UserId = a1.UserId
                        and a2.row_num = a1.row_num + 1
            --order by  a1.UserId, a1.row_num
            ) a
group by    a.ItemId
order by    a.ItemId;

答案 1 :(得分:0)

SELECT ItemId,COUNT(1) VISITS,SUM(BOUNCE_IND) BOUNCE, cast(SUM(BOUNCE_IND) as decimal(5,2))/cast(COUNT(1) as decimal(5,2)) BOUNCE_RATE
FROM (
    Select 
        UserID,
        ItemID,
        DocLocation,
        Occurred as Entry_time,
        Lead(Occurred,1) Over (Partition by Userid order by Occurred) Exit_time,
        CASE WHEN DATEDIFF(ss,Occurred,Lead(Occurred,1) Over (Partition by Userid order by Occurred)) <= 5 THEN 1 ELSE 0 END BOUNCE_IND
    FROM Web_Data_Sample
) TBL GROUP BY ItemId