3

I need to write a query that creates a view that calculates the total cost of each sale, by considering quantity and price of each bought item. The view should return the debit and total cost.

In the answer each debit-number should only occur once.

Thanks in advance

Table ITEM:

ID       NAME       PRICE
118      Jeans      100
120      Towel      20
127      Shirt      55

Table DEBIT:

DEBIT     ITEM     Quantity
100581    118      5
100581    120      1
100586    127      5
3
  • How are these tables related? IS it ITEM->ID? Commented Mar 22, 2012 at 11:37
  • I have tried the following: SELECT debid, (item.price * debit.quantity) AS "Total Price" FROM debit, item WHERE debit.item = item.id Commented Mar 22, 2012 at 11:40
  • @Slinky, yes. The ITEM is related with ID. Commented Mar 22, 2012 at 11:43

3 Answers 3

3

You can try this using a simple JOIN;

SELECT d.DEBIT, SUM(d.Quantity*i.Price) SUM
FROM DEBIT d
JOIN ITEM i ON d.ITEM=i.ID
GROUP BY d.DEBIT;

Simple demo here.

Sign up to request clarification or add additional context in comments.

Comments

2

How about -

SELECT DEBIT.DEBIT, SUM(`ITEM`.`PRICE` * `DEBIT`.`Quantity`)
FROM `ITEM`
INNER JOIN `DEBIT`
    ON `ITEM`.`ID` = `DEBIT`.`ITEM`
GROUP BY `DEBIT`.`DEBIT`

1 Comment

Around here we say thanks by accepting the answer that we use. Please accept @Joachim's answer as he made the effort to set up the demo.
-2

something like this would work...

SELECT d.id,SUM(i.price*d.quantity) as total_cost
FROM item i join debit d 
on i.id=d.item_id 
group by d.id;

2 Comments

You don't want to group by i.price,d.quantity.
yeah..i knw..written by mistake..!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.