You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL中对父主题及其子项进行分组求和?

将子主题订单佣金合并到父主题统计的解决方案

修改后的SQL查询

SELECT 
    parent.name,
    SUM(o.commission_amount) AS commission
FROM orders o
LEFT JOIN topics t ON o.topic_id = t.id
LEFT JOIN topics parent 
  ON COALESCE(t.topic_id, t.id) = parent.id
WHERE parent.topic_id IS NULL
GROUP BY parent.name

逻辑说明

  1. 第一次关联topics表,获取每个订单对应的主题信息;
  2. 第二次关联topics表作为父主题表,通过COALESCE(t.topic_id, t.id)适配两种场景:
    • 若为子主题(t.topic_id非空),关联到它的父主题ID;
    • 若为父主题(t.topic_id为空),关联到自身ID;
  3. 用WHERE parent.topic_id IS NULL筛选出顶级父主题;
  4. 按父主题名称分组,对佣金金额求和。

输出结果

执行上述查询后,将得到符合预期的统计结果:

namecommission
Meal Delivery60
Mattresses150

内容的提问来源于stack exchange,提问作者cjay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 08:54:21