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

如何在主查询中统计sale_shops表店铺数并实现整合?

解决方案

你之前左连接没得到预期结果,大概率是因为直接关联sale_shops和order表后,订单数据的重复导致店铺数被错误统计(比如一个销售有3条订单、2个店铺,直接关联会生成6条记录,统计店铺数时会算成6而不是2)。

可以用两种方式实现需求:

方式一:先预统计店铺数再关联

先对sale_shops按销售人员分组统计店铺数量,再和order表的统计结果左连接,避免数据重复计算:

SELECT 
  o.sales_people_name,
  COUNT(o.amount_sales) AS total_sales,
  SUM(o.price) AS total_price,
  COALESCE(s.shop_count, 0) AS shop_count
FROM `order` o
LEFT JOIN (
  -- 预统计每个销售对应的店铺数,用DISTINCT防止同一店铺被重复统计
  SELECT 
    sales_people_name,
    COUNT(DISTINCT shop_id) AS shop_count
  FROM sale_shops
  GROUP BY sales_people_name
) s ON o.sales_people_name = s.sales_people_name
GROUP BY o.sales_people_name, s.shop_count

方式二:使用关联子查询

在SELECT语句中直接通过子查询获取对应销售的店铺数,逻辑更直观:

SELECT 
  sales_people_name,
  COUNT(amount_sales) AS total_sales,
  SUM(price) AS total_price,
  (
    SELECT COUNT(DISTINCT shop_id) 
    FROM sale_shops s
    WHERE s.sales_people_name = `order`.sales_people_name
  ) AS shop_count
FROM `order`
GROUP BY sales_people_name

关键注意点

  • order是SQL关键字,必须用反引号(`)包裹作为表名
  • total price列名有空格,需要改成total_price或者用反引号包裹
  • 统计店铺数时建议用COUNT(DISTINCT shop_id),避免同一店铺被多次统计(如果sale_shops表中存在同一销售对应同一店铺的多条记录)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:35:18