tags:

views:

41

answers:

2

Hi all,

I have a table Orders with (id,orderCode,productId,quantity,color,size) where I can have entries like:

1,O20100812,163,2,BLUE,Medium
1,O20100812,163,3,BLUE,Larger
1,O20100812,145,4,RED,Large etc
1,O20100815,134,5,RED,Large etc
1,O20100815,143,2,BLACK,Large etc
1,O20100815,112,8,BLACK,Large etc

And another table Products with (id,name,price)

What I want is to find the total price of all the products in the order with orderCode 020100812. Should I DISTINCT select the order code and then SUM the quantity while JOINing the products table?

I am confused

Thanks in advance

+4  A: 

Why you need distinct?

Select SUM(o.Quantity * Price) TotalPrice
FROM Orders o JOIN Products p ON (o.ProductId = p.Id)
WHERE OrderCode = '020100812'

For all orders you can use the following query:

Select OrderCode, SUM(o.Quantity * Price) TotalPrice
FROM Orders o JOIN Products p ON (o.ProductId = p.Id)
Group by OrderCode
Michael Pakhantsov
I think I need DISTINCT cause I can have multiple O20100812 and multiple O20100813 and multiple O20100816 etc
chchrist
No you don't need to specify distinct. @Michael's answer is correct.
Ismail
But I need to show in a html table the orderCode and the total price of the order. With WHERE I'll show only the 020100812. Should I make a query for each order?
chchrist
No, you should `GROUP BY OrderCode` in that case.
Rup
+1  A: 

No, GROUP BY and then you can use SUM to aggregate across the group, e.g.

select  O.id, O.ordercode, sum(P.price * O.quantity) as total
  from  orders O
  join  products P on P.id = O.productid
group by O.id, O.ordercode

which will show you the total price for each order code within each order - if you wanted all order codes across all orders you'd need

select  O.ordercode, sum(P.price * O.quantity) as total
  from  orders O
  join  products P on P.id = O.productid
group by O.ordercode

i.e. don't group in the order ID.

(I'm guessing that O20100812 was just an example and you actually want this for all order codes?)

Rup