xickoh
xickoh

Reputation: 314

Get the total sum of 2 multiplied columns SQL

I have these 3 tables:

Bill:

idBill

Products:

idProduct
price

BillProducts (that connects the tables above):

idBill
idProduct
quantity

Now let's say I wish to get the total price of a certain bill identified by its ID

I would need to multiply the columns of Products.Price by BillProducts.quantity, get its result and sum all the others products in that idBill

Can you guys help me writing that query?

Upvotes: 1

Views: 898

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270873

You would do:

select sum(p.price * bp.product)
from billproducts bp join
     products p
     on bp.idproduct = p.idproduct
where idbill = <idbill>;

You can get this for all bills using group by:

select idbill, sum(p.price * bp.product)
from billproducts bp join
     products p
     on bp.idproduct = p.idproduct
group by idbill;

Notes:

  • You do not need to join the bills table. All the information you need is in the other two tables.
  • You do not need a subquery.
  • When you define table aliases, they should be abbreviations for the table names, so the query is easier to follow.

Upvotes: 1

Ian-Fogelman
Ian-Fogelman

Reputation: 1605

SELECT SUM(QUANTxPRICE) AS SUMED, IDBILL FROM (
SELECT (A.QUANTITY * B.PRICE) AS QUANTxPRICE,a.IDBILL
FROM BILLPRODUCTS AS A
JOIN PRODUCTS AS B ON 
A.IDPRODUCT = B.IDPRODUCT
JOIN BILL AS C
ON A.IDBILL = C.IDBILL
) AS X
GROUP BY IDBILL

enter image description here

Upvotes: 3

Related Questions