如何按brand_id、country_id、app_id分组s2s_actions并统计clicks数量?
解决方案
可以通过以下SQL语句实现需求:
SELECT s.app_id, s.country_id, s.brand_id, COUNT(c.id) AS total_clicks FROM ( -- 提取s2s_actions中唯一的分组组合 SELECT DISTINCT app_id, country_id, brand_id FROM s2s_actions ) s -- 关联clicks表匹配对应分组 LEFT JOIN clicks c ON s.app_id = c.app_id AND s.country_id = c.country_id AND s.brand_id = c.brand_id -- 按分组字段聚合统计 GROUP BY s.app_id, s.country_id, s.brand_id ORDER BY s.brand_id DESC;
逻辑说明
- 子查询
s通过DISTINCT过滤s2s_actions中的重复分组,确保每个app_id+country_id+brand_id组合只出现一次。 - 使用
LEFT JOIN关联clicks表,保证即使s2s_actions的分组在clicks中无匹配记录,也能保留该分组并显示total_clicks为0。 - 通过
COUNT(c.id)统计每个分组对应的clicks记录数,最终按分组字段聚合得到结果。
执行后将得到与预期一致的输出:
app_id country_id brand_id total_clicks ------ ---------- -------- ------------ 15 5 361 1 15 64 7 1 15 5 37 2
内容的提问来源于stack exchange,提问作者trueicecold
相关产品推荐
相关产品推荐

