I want to display all customers and their addresses and the number and total sum of their orders. My query looks like this:
select *, sum(o.tota), count(o.total)
from customer c
natural join orders o
group by c.custId;
which works fine.
but if I add a new table to the query:
select *, sum(o.tota), count(o.total)
from customer c
natural join orders o
natural join cust_addresses a
group by c.custId;
then it won't work anymore. the aggregate functions return wrong values because there may be multiple addresses per customer, which is correct, I also want to display all their addresses. What can I do to solve the aggregate function problem?
I could think of doing something like:
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;
But this is very slow.
EDIT I now tried the following but it tells me that field c.custid is unknown:
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;