Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the SUM of (Quantity*Price) from 2 different tables

Tags:

sql

sum

I have two tables as follows

PRODUCT table

Id | Name | Price

And an ORDERITEM table

Id | OrderId | ProductId | Quantity

What I'm trying to do is, calculate the subtotal price for each product (Quantity*Price) then SUM the TOTAL value for the entire order..

I'm trying something like this

SELECT Id, SUM(Quantity * (select Price from Product where Id = Id)) as qty
FROM OrderItem o
WHERE OrderId = @OrderId

But of course that doesn't work :)

Any help appreciated!

EDIT: I only want to show the grand total for the entire order, so basically the sum of Quantity*Price for every row in OrderItem. Here's some sample data.

Sample Data

TABLE Product

Id     Name            Price  
1      Tomatoes        20.09    
4      Cucumbers       27.72    
5      Oranges         21.13    
6      Lemons          20.05
7      Apples          12.05

Table OrderItem

Id         OrderId        ProductId        Quantity
151        883            1                22
152        883            4                11
153        883            5                8
154        883            6                62

M

like image 869
Marko Avatar asked Aug 17 '10 19:08

Marko


People also ask

How do you sum the value of two columns?

AutoSum function Identify the column you want to sum and select the empty cell immediately below the last value in the column. In the "Home" tab, find the "Editing" group and select the "AutoSum" button, or you can go to the "Formulas" tab and select "AutoSum."

How do you sum price in SQL?

The SUM() function returns the total sum of a numeric column.

How do I add two columns from different tables in SQL?

Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other). Below is the generic syntax of SQL joins. USING (id);


2 Answers

Use:

  SELECT oi.orderid,
         SUM(oi.quantity * p.price) AS grand_total,
    FROM ORDERITEM oi
    JOIN PRODUCT p ON p.id = oi.productid
   WHERE oi.orderid = @OrderId
GROUP BY oi.orderid

Mind that if either oi.quantity or p.price is null, the SUM will return NULL.

like image 93
OMG Ponies Avatar answered Sep 30 '22 03:09

OMG Ponies


i think this - including null value = 0

 SELECT oi.id, 
         SUM(nvl(oi.quantity,0) * nvl(p.price,0)) AS total_qty 
    FROM ORDERITEM oi 
    JOIN PRODUCT p ON p.id = oi.productid 
   WHERE oi.orderid = @OrderId 
GROUP BY oi.id 
like image 45
Randy Avatar answered Sep 30 '22 03:09

Randy