如何组合 2 个 SQL 查询并检索累积计数?
Posted
技术标签:
【中文标题】如何组合 2 个 SQL 查询并检索累积计数?【英文标题】:How can I combine 2 SQL queries and retrieve a cumulative count? 【发布时间】:2015-12-14 12:57:53 【问题描述】:我正在尝试检索特定 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
转化结果:
如果我能检索到运行总(累积)计数,那就太好了,如下所示,请参阅最后 2 列。我已按组合对下表进行分组,以便更容易理解累积计数:
+---------------+-------------+----------------------+-----------------+--------------+--------------+
| 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 |
+---------------+-------------+----------------------+-----------------+--------------+--------------+
数据库架构:
【问题讨论】:
【参考方案1】:组合很简单:添加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,但它们非常棘手。
【讨论】:
非常感谢 Timekiller :) 这行得通,我正在 php 中进行运行总计。我试过了,但在 MySQL 中为每个组合计算运行总计似乎并不简单,但感谢您的链接。【参考方案2】:我希望这会有所帮助。
SELECT DATE(v.created), v.combination ,DATE(c.created), c.combination, COUNT(v.id), COUNT(c.id) FROM user u
LEFT JOIN conversion c ON u.id = c.user_id
LEFT JOIN visit v ON u.id = v.user_id
WHERE c.id = 6 AND v.experiment_id = 1 AND c.goal_id = 1
GROUP BY DATE(v.created), v.combination, DATE(c.created), c.combination
【讨论】:
请解释一下你的答案。以上是关于如何组合 2 个 SQL 查询并检索累积计数?的主要内容,如果未能解决你的问题,请参考以下文章