How to create a function that totals an order with several items? - sql

I need to create a function which will return the total of an order. I've been given three tables with the following variables
Table 1 - Order
Order_ID
Date_Placed
Date_Fulfilled
Table 2 - Order Product
Order_ID
Product_ID
Product_Quantity
Table 3 - Product
Product_ID
Price
I'm struggling to put together a coherent function. Any help would be greatly appreciated.
I've already attempted to set up the function with joins between both tables, but am unable to figure out where I should be putting my equation.
BEGIN
SELECT order.order_id, SUM(product.price * order_item.quantity)
FROM `order`
JOIN `order_item` ON order.order_id = order_product.order_id
JOIN `product` ON order_product.product_id = product.product_id;
END $$

You might be surprised, but the orders table is not needed for this query. You can just aggregate off the other two tables:
SELECT oi.order_id, SUM(p.price * oi.quantity)
FROM order_item oi JOIN
product p
ON po.product_id = p.product_id
GROUP BY oi.order_id;

You'll need to take your select statement, and group it by your order.order_id. That way you'll have one row per order, with the sum total of that order.
SELECT order.order_id, SUM(product.price * order_item.quantity) as total_price
FROM `order`
JOIN `order_item` ON order.order_id = order_product.order_id
JOIN `product` ON order_product.product_id = product.product_id
GROUP BY order.order_id

this will work:
SELECT order.order_id, SUM(product.price * order_item.quantity)
FROM order o,
JOIN order_item oi,
JOIN product p where
o.order_id = oi.order_id and
oi.product_id = p.product_id
group by order_product.product_id = product.product_id;

Related

SQL - Sum Up Results Of A Multiplication By Group

I have the following tables:
Orders (OID, Count, ProductID, TableNr)
Table (TableNr, Name, Number)
Products (ProductID, Prize)
Now I want to calculate how much was earned per table. I think to do this I have to Group By Orders.TableNr. But how can I multiply the Products.Prize with the Orders.Count and after that sum up this results within the group?
You are describing a join and aggregation:
select o.tableNr, sum(o.count * p.prize) totalEarned
from orders o
inner join products p on p.productId = o.productId
group by o.tableNr
If you want to display table information as well (say, the table name), then you can add another join:
select t.tableNr, t.name, sum(o.count * p.prize) totalEarned
from table t
inner join orders o on o.tableNr = t.tableNr
inner join products p on p.productId = o.productId
group by t.tableNr, t.name
Note that table is a SQL keyword, hence not a good choice for a table name.

sql get newest date and price of all inventory_items

I have this sql tables, and i need to get from all inventory items the newest date from table: orders with the price paid on this date
table:orders
id
date
table:order_items
order_id
inventory_id
price
table:inventory
item_number
if i do something like that:
SELECT inventory.item_number, orders.date, order_items.price
FROM inventory
INNER JOIN order_items ON inventory.id = order_items.inventory_id
INNER JOIN orders ON order_items.order_id = orders.id
WHERE max(orders.date)
it's not working, and i get an error.
What is the correct way to do that
You need a where clause, but the MAX() cannot go there directly. Try a subquery:
SELECT i.item_number, o.date, orders.price
FROM inventory i INNER JOIN
order_items oi
ON i.id = oi.inventory_id INNER JOIN
orders o
ON oi.order_id = o.id
WHERE o.date = (SELECt max(o2.date) FROM orders o2);

SQL sum from single table with join

I have two table orders and orderitems.
order table has id,order_total,recieved_amount
orderitems table has id,order_id,name,total_item
I want the sum of recieved_amount, order_total from the order table and sum of total_item from orderitems. so I used
SELECT SUM(`received_amount`) as totalRecieved,
SUM(`order_total`) as orderTotal
FROM `orders` AS `Order`
LEFT JOIN `order_items` AS `OrderItems`
ON (`OrderItems`.`order_id`=`Order`.`id`)
and
SELECT SUM(`received_amount`) as totalRecieved,
SUM(`order_total`) as orderTotal
FROM `orders` AS `Order`
LEFT JOIN `order_items` AS `OrderItems`
ON (`OrderItems`.`order_id`=`Order`.`id`)
group by order.id
but none of them is giving me the correct result.
You are aggregating at two levels of your data hierarchy. This causes a problem with Cartesian products, for each order.
The solution is to aggregate along order_items before doing the join:
SELECT SUM(received_amount) as totalRecieved,
SUM(order_total) as orderTotal
FROM orders o LEFT JOIN
(SELECT oi.order_id, SUM(total_items) as total_items
FROM order_items oi
GROUP BY oi.order_id
) oi
ON oi.order_id = o.id;
As an alternative, you can benefit from cte structure or a temp table like below:
;with cte (order_id, SumTotalItems) as (
SELECT oi.order_id, SUM(total_items) as SumTotalItems
FROM order_items oi
GROUP BY oi.order_id
)
select sum(o.receivedamount) as SumReceivedAmount
, sum(o.order_total) as SumOrderTotal
, cte.SumTotalItems
from orders o
left outer join cte on o.id = cte.order_id

SQL Join with SUM()

I have two Tables
Product Details(About Product)
Sale Order Details(What Price is sold, quantity of products sold per order).
I am trying to do Join on Table 1 and Table 2 which should give the all the product details and sum(Quantity), Sum(Price)
Problem Facing: There are some products in Table 1 which are never sold, and those rows are missing in the result set, but I want details for all the rows in Table 1 with rows of Products never purchased should be NULL or 'o'
Query I am Using:
select
P.*,
ISNULL((sum([Q.Quantity])),0),
ISNULL((sum([Q.Price])),0)
From Table1 P
Left Outer Join Table2 Q on P.Product_ID = Q.Product_ID
Please help me with any suggestions that would work for me
How about this one:
select
P.Product_ID,
ISNULL(sum([Q.Quantity]),0),
ISNULL(sum([Q.Price]),0)
From Table1 P
Left Outer Join Table2 Q
on P.Product_ID = Q.Product_ID
group by
P.Product_Id

sql issue to query product name

I am new to SQL , I have been looking for on line resources but have not find anything yet to solve my problem. Basically i have three tables below:
ORDERTBL(ORDERID,ORDERDATE,ORDERSTATUS),
PRODUCT(PRODUCTID,PRODUCT_NAME),
ORDERLINKPRODUCTS(ORDERID,PRODUCTID,QUANTITY,ORDERLINKPRODUCTID)
I want to get all the product name from the products tables for a specific order which i should query from ORDERLINKPRODUCTS since it contains all the orders.
for instance please find test data available in 3 tables:
Table ORDERTBL:
ORDERID=1,ORDERDATE= 24May, ORDERSTATUS=Process
Table PRODUCTS:
PRODUCID =1 PRODUCT_NAME = spoon PRODUCID =2 PRODUCT_NAME = soap
Table :ORDERLINKPRODUCTS:
ORDERID=1 PRODUCTID = 1 QUANTITY=3 ORDERLINKPRODUCTID=1 ORDERID=1 PRODUCTID = 2 QUANTITY=1 ORDERLINKPRODUCTID=2
I am trying to make a select statements that display all the product name of an order. For instance display all product name of orderid=1 which will return spoon,soap.
Any suggestion how to do it please?
Thanks in advance.
You should use JOIN keyword in SQL to join the three tables to be able to access PRODUCTNAME and show that table data. More about Join clause
SELECT prod.PRODUCT_NAME
FROM ORDERTBL ord
INNER JOIN ORDERLINKPRODUCTS link ON ord.ORDERID = link.ORDERID
INNER JOIN PRODUCT prod ON link.PRODUCTID = prod.PRODUCTID
WHERE ord.ORDERID = 1
SQLfiddle Demo
You can find orders with products ilsted using this
SELECT O.ORDERID, RTRIM(
XMLAGG(XMLELEMENT(e, P.PRODUCT_NAME ||',') ORDER BY O.ORDERID).EXTRACT('//text()'), ',') as Products
FROM ORDERTBL O
INNER JOIN ORDERLINKPRODUCTS L
ON O.ORDERID = L.ORDERID
INNER JOIN PRODUCT P
ON L.PRODUCTID = P.PRODUCTID
GROUP BY O.ORDERID
and products listed with its quantity using this:
SELECT O.ORDERID, RTRIM(
XMLAGG(XMLELEMENT(e, P.PRODUCT_NAME || '(' || L.QUANTITY || '),') ORDER BY O.ORDERID).EXTRACT('//text()'), ',') as Products
FROM ORDERTBL O
INNER JOIN ORDERLINKPRODUCTS L
ON O.ORDERID = L.ORDERID
INNER JOIN PRODUCT P
ON L.PRODUCTID = P.PRODUCTID
GROUP BY O.ORDERID
You can add WHERE clause clause to filted orders as you whish.
SQL FIDDLE DEMO