我正在尝试检索特定 A/B 测试组合每天的访问次数和转化次数。每个组合代表 A/B 测试的不同变体。在这里,我仅使用 '1'
和 '2'
来表示变体,但从技术上讲,可能会有更多变体。
我编写了以下 2 个独立工作的查询。是否可以组合这些或编写一个查询来检索我想要的数据?
访问查询:
SELECT DATE(visit.created), visit.combination, COUNT(visit.id)
FROM visit
WHERE visit.user_id = 6
AND visit.experiment_id = 1
GROUP BY DATE(visit.created), visit.combination
访问结果:
转化查询:
SELECT DATE(conversion.created), conversion.combination, COUNT(conversion.id)
FROM conversion
WHERE conversion.user_id = 6
AND conversion.experiment_id = 1
AND conversion.goal_id = 1
GROUP BY DATE(conversion.created), conversion.combination
转化结果:
另外,如果我能检索到运行总(累积)计数,那就太好了,如下所示,请参阅最后两列。我按组合对下表进行了分组,这样累计计数更容易理解:
+---------------+-------------+----------------------+-----------------+--------------+--------------+
| DATE(created) | combination | COUNT(conversion.id) | COUNT(visit.id) | cumulative_c | cumulative_v |
+---------------+-------------+----------------------+-----------------+--------------+--------------+
| 2015-11-17 | 1 | 1 | 3 | 1 | 3 |
| 2015-11-18 | 1 | 7 | 4 | 8 | 7 |
| 2015-11-19 | 1 | 3 | 8 | 11 | 15 |
| 2015-11-17 | 2 | 4 | 1 | 4 | 1 |
| 2015-11-18 | 2 | 2 | 6 | 6 | 7 |
| 2015-11-19 | 2 | 9 | 6 | 15 | 13 |
+---------------+-------------+----------------------+-----------------+--------------+--------------+
数据库模式:
最佳答案
合并非常简单:添加 0 值列,执行 UNION_ALL
,然后再次分组并求和。
SELECT dt, combination, SUM(v_count) as v_count, SUM(c_count) as c_count
FROM
(
SELECT DATE(visit.created) as dt, visit.combination as combination, COUNT(visit.id) as v_count, 0 as c_count
FROM visit
WHERE visit.user_id = 6
AND visit.experiment_id = 1
GROUP BY DATE(visit.created), visit.combination
UNION ALL
SELECT DATE(conversion.created) as dt, conversion.combination as combination, 0 as v_count, COUNT(conversion.id) as c_count
FROM conversion
WHERE conversion.user_id = 6
AND conversion.experiment_id = 1
AND conversion.goal_id = 1
GROUP BY DATE(conversion.created), conversion.combination
) as t
GROUP BY dt, combination
现在,计算总计。在更高级的 DBMS 中,这称为“窗口”或“分析”函数。例如,在 Oracle 中你可以这样做:
SELECT dt, combination, SUM(v_count) OVER (PARTITION BY combination ORDER BY dt) as v_cumulative
对于上面的查询,它会给你你想要的。但是,MySQL 没有这样的功能。有方法绕过,描述here和 here例如,但它们非常棘手。
关于mysql - 如何组合 2 个 SQL 查询并检索累计计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34267673/