首页 > 解决方案 > 按来源统计每次购买前 30 天的访问次数

问题描述

我有一个记录网站活动的表格,其中包含以下列和数据

ID  Date         Source  Revenue

1   2013-10-01   A       0
2   2013-10-01   A       0
3   2013-10-01   B       10
1   2013-10-02   A       40
4   2013-10-03   B       0
3   2013-10-03   B       0
4   2013-10-04   A       10

我正在尝试创建一个表,该表接受每笔交易(收入 > 0)并计算过去 30 天内各个列中的所有来源访问。它应该看起来像这样。

ID  Date         Source  Revenue Count_A  Count_B

3   2013-10-01   B       10      0        1
1   2013-10-02   A       40      2        0
4   2013-10-04   A       10      1        1

我已经尝试对这些列中的每一列使用子查询,但是计数很差,我不知道为什么。

Select ID,
       Date,
       Source,
       Revenue,
       (SELECT Count(*) 
               FROM table t2
               WHERE t2.Date between t.Date-30 and t.Date and Source = 'A') AS Count_A
       (SELECT Count(*) 
               FROM table t3
               WHERE t3.Date between t.Date-30 and t.Date and Source = 'B') AS Count_B
  FROM table t
  Where Revenue > 0
  Order By WMEID

我正在使用 Microsoft SQL Server。

标签: sqlsql-servertsqlcounte-commerce

解决方案


使用横向连接:

Select l.*, l2.*
from logs l outer apply
     (select sum(case when l2.source = 'A' then 1 else 0 end) as count_a,
             sum(case when l2.source = 'B' then 1 else 0 end) as count_b
      from logs l2
      where l2.id = l.id and
            l2.date >= dateadd(day, -30, l.date) and
            l2.date <= l.date
     ) l2
where l.Revenue > 0
order By l.WMEID;

我认为您的方法的问题在于您不匹配 ID。


推荐阅读