【发布时间】:2011-03-20 23:57:47
【问题描述】:
我想显示所有客户及其地址以及他们的订单数量和总和。我的查询如下所示:
select *, sum(o.tota), count(o.total)
from customer c
natural join orders o
group by c.custId;
效果很好。
但是如果我在查询中添加一个新表:
select *, sum(o.tota), count(o.total)
from customer c
natural join orders o
natural join cust_addresses a
group by c.custId;
那么它将不再起作用。聚合函数返回错误值,因为每个客户可能有多个地址,这是正确的,我还想显示他们的所有地址。 如何解决聚合函数问题?
我可以考虑做这样的事情:
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;
但这很慢。
编辑 我现在尝试了以下操作,但它告诉我字段 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;
【问题讨论】:
-
你想如何处理没有订单的客户?您当前的查询忽略了它们。
-
右年,我忘记了左连接的左边:)
标签: sql sqlite select aggregate-functions