Link to home
Start Free TrialLog in
Avatar of moraleskp
moraleskp

asked on

special join between 3 tables

I need a query to find an totals for items and writeins for each company.  I have an Order table, an Orderdetails table, and a OrderWritein table.  Both OrderDetails and OrderWriteIns have a Price and Quantiy column.  I wrote this with joins as follows:
Select C.CompanyName,sum(D.price*D.Quantity) itmAmt,sum (W.price*W.Quantity) wiAmt,max(O.OrderDate) [Last Order]
From tblOrders O
Inner Join tblCompany C on O.companyid = C.companyid
Inner Join tblOrdersDetail D on O.orderid=D.orderid
Inner Join tblOrdersWriteIns W on O.orderid=W.orderid
group by C.companyName

The problem is when I join the write in table it does a cross join.  if I have 10 items and 10 writeIns then the sum is for the 100 rows.  How do I write the query so each company has the correct sum for both itemsDetail and writeIns?
Avatar of imitchie
imitchie
Flag of New Zealand image

Select C.CompanyName,
 (select sum(D.price*D.Quantity) from tblOrdersDetail D where O.orderid=D.orderid) itmAmt,
 (select sum (W.price*W.Quantity) from tblOrdersWriteIns W where O.orderid=W.orderid) wiAmt,
 max(O.OrderDate) [Last Order]
From tblOrders O
Inner Join tblCompany C on O.companyid = C.companyid
group by C.companyName
ASKER CERTIFIED SOLUTION
Avatar of imitchie
imitchie
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of moraleskp
moraleskp

ASKER

imitchie,
Thanks for responding.
on the first response I got an error saying orderid was not in the group by clause.
In the second response got an error that orderId is an invalid column.  I guess because it is not selected in the sub query.
Your responses gave me some ideas so I tried the following code.  It seems to work.  



select companyName,sum(itmAmt),sum(wiAmt),max(Orderdate)
from
(Select O.orderid,C.CompanyName,
(select sum(D.PriceSold*D.qty) from tblOrdersDetail D where O.orderid=D.orderid)itmAmt,
(select sum(W.RetailPrice*W.Qty) from tblOrders_Writeins W where O.orderid=W.orderid) wiAmt,
O.orderdate
from tblOrders O
inner join tblCompany C on O.companyid=C.companyid
Group by C.companyName,O.orderid,O.orderdate
) query
group by companyName
Order by CompanyName

Open in new window

You are right. Good on you to find a solution! This would probably have worked, and does less work

Select OC.CompanyName,
 (select sum(D.price*D.Quantity) from tblOrdersDetail D where OC.orderid=D.orderid) itmAmt,
 (select sum (W.price*W.Quantity) from tblOrdersWriteIns W where OC.orderid=W.orderid) wiAmt,
 OC.[Last Order]
From (
 select O.OrderID, C.CompanyName, max(O.OrderDate) [Last Order]
 FROM tblOrders O
 Inner Join tblCompany C on O.companyid = C.companyid
 group by C.companyName
) OC
nvm, orderid is not in the group by..