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

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

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.

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

I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.
select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
select o.orderID, o.price * o.qty as subtotal
from product p inner join orderitem o on p.ProductID= o.productID
where o.orderID = #OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal

select orderID, sum(subtotal) as order_total from
(
select orderID, productID, price, qty, price * qty as subtotal
from product p inner join orderitem o on p.id = o.productID
where o.orderID = #orderID
) t
group by orderID

I had the same problem as Marko and come across a solution like this:
/*Create a Table*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Create a Stored Procedure*/
CREATE PROCEDURE GetGrandTotal
AS
/*Delete the 'tableGrandTotal' table for another usage of the stored procedure*/
DROP TABLE tableGrandTotal
/*Create a new Table which will include just one column*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Insert the query which returns subtotal for each orderitem row into tableGrandTotal*/
INSERT INTO tableGrandTotal
SELECT oi.Quantity * p.Price AS columnGrandTotal
FROM OrderItem oi
JOIN Product p ON oi.Id = p.Id
/*And return the sum of columnGrandTotal from the newly created table*/
SELECT SUM(columnGrandTotal) as [Grand Total]
FROM tableGrandTotal
And just simply use the GetGrandTotal Stored Procedure to retrieve the Grand Total :)
EXEC GetGrandTotal

Related

Order Line quantity sum total SQL calculation

I have Order:
I have OrderLine:
I want to show which product has been sold the most.
I want to sum every quantity in orderline where it belongs to an order which has status 'completed'
Looking at the data, we see only orderID = 3 has orderstatus = Completed, therefore we only want OrderLine for OrderID = 3 - which is OrderLineID = 6 and OrderLineID = 7.
So our expected result would be ProductID 1 with Quantity 11 as follows:
ProductID|OrderLineQuantity
-------1-----|----------11-----------
My code so far produces an error:
Column 'OrderLine.ProductID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
My code:
SELECT OrderLine.ProductID, SUM(OrderLineQuantity)FROM OrderLine Inner Join [Order] ON OrderLine.OrderID = [Order].OrderID WHERE OrderStatus = 'Completed'
You need a GROUP BY to fix the syntax problem, and then something else to get the top product:
SELECT TOP (1) ol.ProductID, SUM(ol.OrderLineQuantity)
FROM OrderLine ol Inner Join
[Order] o
ON ol.OrderID = o.OrderID
WHERE o.OrderStatus = 'Completed'
GROUP BY ol.ProductID
ORDER BY SUM(ol.OrderLineQuantity) DESC;

How to multiply 2 columns and then SUM the results?

I'm learning SQL and I couldn't find the solution to my problem anywhere on he forums. Anyway, I'm using a www.dofactory.com SQL Sandbox and I've made a query:
select customer.LastName, Product.ProductName, OrderItem.Quantity, Product.UnitPrice, OrderItem.Quantity*Product.UnitPrice AS "Quantity x UnitPrice"
FROM Customer
JOIN [Order] ON [Order].CustomerID = Customer.ID
JOIN OrderItem ON OrderItem.OrderId = [Order].ID
JOIN Product ON Product.Id = OrderItem.ProductId
where
[Order].TotalAmount = (select max([Order].TotalAmount) FROM [Order])
And result:
LastNam ProductName Quantity UnitPrice Quantity x UnitPrice
Kloss Côte de Blaye 60 263.50 15810.00
Kloss Chartreuse verte 80 18.00 1440.00
Now I want to SUM the whole Column "Quantity x UnitPrice". What should I do?
You use SUM(). Something like this:
SELECT SUM(oi.Quantity * oi.UnitPrice) AS Summary
FROM Customer c JOIN
[Order] o
ON o.CustomerID = c.ID JOIN
OrderItem oi
ON oi.OrderId = o.ID JOIN
Product p
ON p.Id = oi.ProductId
WHERE o.TotalAmount = (select max(o2.TotalAmount) FROM [Order] o2);
Note the use of table aliases. They make the query easier to write and to read.
This is SQL Server (T-SQL). You can use SUM and GROUP BY like so. I've done it in a subquery, which is how I'd approach this sort of thing.
select LastName, ProductName, Quantity, UnitPrice, SUM(Summary)
from (
select customer.LastName, Product.ProductName, OrderItem.Quantity, Product.UnitPrice, OrderItem.Quantity*OrderItem.UnitPrice AS Summary, [Order].TotalAmount
FROM Customer
JOIN [Order] ON [Order].CustomerID = Customer.ID
JOIN OrderItem ON OrderItem.OrderId = [Order].ID
JOIN Product ON Product.Id = OrderItem.ProductId
where
[Order].TotalAmount = (select max([Order].TotalAmount) FROM [Order])) x
group by LastName, ProductName, Quantity, UnitPrice

Select From 2 Selects

I need some help I have 3 tables
http://i.stack.imgur.com/TB3MX.jpg
My code:
select nazev_produkt,
SUM(mnozstvi_objednavka_dod)'bylo na sklade'
from Produkty p join Objednavky_dodavatele od on
p.id_produkt=od.id_produkt
where stavzbozi_objednavka_dod=('na skladě')
group by nazev_produkt
select nazev_produkt,SUM(mnozstvi_objednavka_zak)koupili
from Objednavky_zakaznici oz join Produkty p
on oz.id_produkt=p.id_produkt
where stav_objednavka_zak=('dodané')
group by nazev_produkt
I want to create select code from both of this selected which will consist of nazev_produkt, 'bylo na sklade - koupili' and group by nazev_produkt
basically
bylo na sklade = was in stock
koupili = purchased.
I need to deduct the purchased - was in stock and show nazev_produkt (Product Name), na sklade (In Stock)
Help is much appreciated!
I can't read your language, so making a few guesses here... :-) The table joining, I think, answers your question in any case.
select
p.product_name,
--isnull(i.quantity,0) as was_in_stock,
--isnull(s.quantity,0) as sold,
isnull(i.quantity,0) - isnull(s.quantity,0) as [currently_in_stock]
from
products p
LEFT JOIN (select product_id, sum(quantity) as quantity from inventory group by product_id) i
ON p.product_id = i.product_id
LEFT JOIN (select product_id, sum(quantity) as quantity from sales group by product_id) s
ON p.product_id = s.product_id
group by
product_name
Add a third column with the typization of your source.
Try this:
select nazev_produkt,
isnull(
(select SUM(mnozstvi_objednavka_dod)
from Objednavky_dodavatele od
where p.id_produkt=od.id_produkt),
0) -
isnull(
(select SUM(mnozstvi_objednavka_zak)
from Objednavky_zakaznici oz
where oz.id_produkt=p.id_produkt),
0)
from Produkty p
where stavzbozi_objednavka_dod=('na sklade')
or stav_objednavka_zak=('dodané')

How filter tables in sql in group

I have two tables.
Customer | OrderItems
CustomerID CustomerName | OrderItemID OrderID CustomerID Status
1 ABC | 1 1 1 Started
2 1 1 Started
| 3 1 1 NotStarted
Now I want to get the record of all the customer where the status of orderItems is Completed. Means in this case the order is incomplete.
so If I want to get the status of incomplete orders it should give me for customer 1 is order1.
even though the items are started of 1st two but still I want to get that Incomplete.
Not sure if I understood you correctly, but this should do the job:
select distinct c.CustomerId, oi.OrderId
from Customer c
inner join OrderItems oi on c.CustomerID = oi.CustomerID
where c.OrderId not in (select o.OrderId from OrderItems o where o.Status <> 'Started')
select OrderID, CustomerID,
SUM(case Status when 'Started' Then 0 Else 1) NS
from OrderItems
having NS > 0;
If you only want the customers with NO INCOMPLETE ORDERS, then this should do the trick:
SELECT C.CustomerID, C.CustomerName
FROM Customer AS C
WHERE (((C.CustomerID) Not In
(SELECT DISTINCT [O].CustomerID
FROM OrderItems AS O
WHERE ((([O].Status)="NotStarted")))));
I miss something though: I think there should be an ORDER table with information regarding the order. Data in your OrderItems table would be inconsistent if you changed the customerID for one record let's say for OrderItemID = 3 the clientID is 2. Are there two different clients for the same order? I suppose that you didn't handle all the information and that there is an Order table.
Regards,
select OrderID, CustomerID,
SUM(case Status when 'NotStarted' Then 1 Else 0) NS
from OrderItems
group by OrderID, CustomerID
having NS > 0;
select c.customerId,c.Customername,O.OrderID, from Customer c left join OrderItem O on C.customerID = o.OrderID where o.Status = 'started'

SQL Query - Understanding the Syntax

I want to display greatest selling product by quantity
Product Table
ProductID ProductName
1 AA
2 BB
3 CC
[Order Details] Table
OrderID ProductID Quantity DateOfOrder
1 1 10 SomeDate
2 1 100 ,,
3 2 15 ,,
4 1 15 ,,
5 2 20 ,,
6 2 30 ,,
7 1 100 ,,
Expected Output
Product By Quantity AA
Because sum(quantity)= 225
I used:
select 'Product By Quantity' + ProductName
from
Products
where ProductID in
(select
ProductID
from
[Order Details] det
where Quantity=
(
select max(SUM(Quantity))
from [Order Details] od
where
od.ProductID=det.ProductID
)
)
I got error : "Cannot perform an aggregate function on an expression containing an aggregate or a subquery"
Please explain me why the syntax fails here so that in future i will write appropriate query by
knowing the correct syntax.Also give me the correct query.
Thank you everybody in advance.
Edit
I was trying for the following query
SELECT 'Best Selling Product'+ProductName
FROM
Products
WHERE ProductID =
(
SELECT ProductID
FROM [Order Details]
GROUP BY ProductID
HAVING SUM(Quantity) = (
SELECT MAX(SQ)
FROM (
SELECT SUM(Quantity) as SQ
FROM [Order Details]
GROUP BY ProductID
) AS OD))
I think this is what you're trying to get to:
select top 1 p.product_name, sum(od.quantity) as total_quantity
from products p
inner join [order details] od
on p.productid = od.productid
group by p.productid, p.product_name
order by total_quantity desc
Try this:
select 'Product By Quantity' + ProductName from Products p
join
(
select top 1 sum(Quantity) sq, od.ProductId
from [Order Details] od
group by od.ProductId
order by 1 desc
) bsp on p.productid = bsp.ProductId
bsp stands for Best Selling Product
looks like select max(SUM(Quantity)) is wrong. The maximum of the sum doesn't have any meaning. Did you mean max(Quantity)?
Try this:
SELECT TOP 1
SUM(o.Quantity)
,p.ProductName
FROM [Order Details] AS o
INNER JOIN [Products] AS p ON p.ProductID = o.ProductID
GROUP BY p.ProductID
,p.ProductName
ORDER BY SUM(o.Quantity) DESC