sql - 按来源统计每次购买前 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。
解决方案
使用横向连接:
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。
推荐阅读
- android - 在提醒通知期间关闭设备后启动 Android 10 全屏意图
- unit-testing - 使用 xUnit 对内存泄漏进行单元测试
- python - 比较数组与python中多行的匹配
- c++ - 如何声明某个结构的成员变量类型的变量?
- bash - bash中具有多个条件的for循环
- matlab - 根据值对结构中的字段进行排序
- scheme - 为什么这个表达式的计算结果为 4 (call/cc)
- node.js - 在 mvc express 项目的 views 文件夹中使用 react
- xampp - xampp上的mysql服务器不起作用
- javascript - !!!foo 和 !foo 一样吗?