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

多表关联时如何正确统计列总和?

一对多关联后求和重复统计的问题

当主表与子表进行一对多关联后,直接对主表字段求和会出现重复统计的问题——主表的每一行会被子表的多行匹配,导致主表字段被多次累加。

由于业务需要筛选t_manufacturer.type = 'some value'的订单数据,必须通过t_orders -> t_cart -> t_products -> t_manufacturer的关联链路实现筛选,无法直接单独统计主表数据。

表结构

create table t_orders (
    oid int,
    cartlink nvarchar(3),
    ordertotal float,
    ordertax float
);
create table t_cart (
    cartlink nvarchar(3),
    productid int
);

测试数据

基础测试数据:

insert into t_orders (oid,cartlink,ordertotal,ordertax) values
    (1,'abc',10, 2),
    (2,'cdf',9, 1),
    (3,'zxc',11, 3)
;
insert into t_cart (cartlink,productid) values
    ('abc', 123),('abc', 321),('abc', 987),
    ('cdf', 123),('cdf', 321),('cdf', 987),
    ('zxc', 123),('zxc', 321),('zxc', 987)
;

更贴合实际场景的测试数据(此时用DISTINCT统计ordertotal会丢失订单2和3的区分,因为二者金额相同):

insert into t_orders (oid,cartlink,ordertotal,ordertax) values
    (1,'abc',10, 2),
    (2,'cdf',9, 1),
    (3,'zxc',9, 3)
;

错误查询及结果

执行以下关联求和查询:

SELECT
    SUM(t_orders.ordertotal) AS SumOfTotal,
    SUM(t_orders.ordertax)   AS SumOfTax
FROM
    t_orders
JOIN t_cart ON t_orders.cartlink = t_cart.cartlink
;

得到的错误结果:

SumOfTotalSumOfTax
9018

期望结果

正确的求和结果应该是:

SumOfTotalSumOfTax
306

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:36:18