连接更多表时聚合函数返回错误值

cod*_*nix 2 sql sqlite select aggregate-functions

我想显示所有客户及其地址以及订单数量和总金额。我的查询如下所示:

select *, sum(o.tota), count(o.total) 
from customer c 
natural join orders o
group by c.custId;
Run Code Online (Sandbox Code Playgroud)

效果很好。

但如果我向查询添加一个新表:

select *, sum(o.tota), count(o.total) 
from customer c 
natural join orders o
natural join cust_addresses a
group by c.custId;
Run Code Online (Sandbox Code Playgroud)

那么它就不再起作用了。聚合函数返回错误的值,因为每个客户可能有多个地址,这是正确的,我也想显示他们的所有地址。我该如何解决聚合函数问题?

我可以考虑做类似的事情:

select *, (select total from orders o where o.custid=c.custid), ..
from customer c 
natural join orders o
natural join cust_addresses a
group by c.custId;
Run Code Online (Sandbox Code Playgroud)

但这非常慢。

编辑 我现在尝试了以下操作,但它告诉我字段 c.custid 未知:

select *
from
     customer c,               
     left join (select sum(o.tota), count(o.total) from orders o where o.custid=c.custid) as o
where ...
group by c.custId;
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

简单的解决方案:使用两个查询。

否则,您可以在子查询中进行聚合计算(在整个表上,而不是每行),然后将子查询的结果与地址表连接起来以获得额外的数据。尝试这个:

SELECT *
FROM customer T1
LEFT JOIN
(
    SELECT custId,
           SUM(total) AS sum_total,
           COUNT(total) AS count_total
    FROM orders
    -- WHERE ...
    GROUP BY custId
) T2
ON T1.custId = T2.custId
-- WHERE ...
Run Code Online (Sandbox Code Playgroud)