Average Price per column within different tables - sql

I'm stumped in trying to complete a problem I was tasked in getting solved.
I'm tasked with doing the following: Calculate the average cost for different products and group them by the category of the product.
How can I do this against different tables?

I see. You want the "average" per "product", not over all the products. So, you need to calculate this yourself using COUNT(DISTINCT):
SELECT p.category AS category_id,
SUM(s.selling_price::numeric) / COUNT(DISTINCT p.product_id)
FROM product p JOIN
supply s
ON p.product_id = s.product_id
GROUP BY p.category;

Related

What's the use of this WHERE clause

this is an answer to the question : We need a list of customer IDs with the total amount they have ordered. Write a SQL statement to return customer ID (cust_id in the Orders table) and total_ordered using a subquery to return the total of orders for each customer. Sort the results by amount spent from greatest to the least. Hint: you’ve used the SUM() to calculate order totals previously.
SELECT prod_name,
(SELECT Sum(quantity)
FROM OrderItems
WHERE Products.prod_id=OrderItems.prod_id) AS quant_sold
FROM Products
;
So there is this simple code up here, and I know that this WHERE clause is comparing two columns in two different tables. But since We are calculating the SUM of that quantity, why do need that WHERE clause exactly. I really couldn't get it. Why the product_id exactly and not any other column ( p.s: the only shared column between those two tables is prod_id column ) I am still a beginner. Thank you!
First you would want to know the sum for each product - so need to adjust the subquery similar to this:
(SELECT prod_id, Sum(quantity) qty
FROM OrderItems
group by prod_id
) AS quant_sold
then once you know how much for each product, then you can link that
SELECT prod_name,
(SELECT prod_id, Sum(quantity) qty
FROM OrderItems
group by prod_id
) AS quant_sold
FROM Products p
WHERE p.prod_id = quant_sold.prod_id
Run it without the where clause and compare the results. You'll learn a lot that way. specifically focus on two different product Ids ensuring they both have order items and quantities.
You have two different tables involved. There are multiple products. You don't want the sum of all orders on each product; which is what you would get without the where clause. So the where clause correlates the two tables ensuring you only SUM the quantity of each order item for each product between the tables. Personally, I'd use a join, sum, and a group by as I find it easier to read and I'm not a fan of sub selects in the select of another query; but that's me.
SELECT prod_name,
(SELECT Sum(quantity)
FROM OrderItems
WHERE Products.prod_id=OrderItems.prod_id) AS quant_sold
FROM Products
Should be the same as:
SELECT prod_name, Sum(coalesce(P.quantity,0))
FROM Products P
LEFT JOIN orderItems OI
on P.prod_id=OI.prod_id
GROUP BY Prod_Name
'Notes
the above is untested.
a left join is needed because all products should be listed and if a product doesn't have an order, the quantity would be zero.
if we use an inner join, the product would be excluded.
We use coalesce because you'd have a "Null" quantity instead of zero for such lines without an order item.
as to which is "right" well it depends and varies on different cases. each has it's own merits and in different cases, one will perform better than another, and in a different case, vice-versa. See --> Join vs. sub-query
As an example:
Say you have Products A & B
"A" has Order Item Quantities of 1 & 2
"B" has order item Quantities of 10 & 20
If we don't have the where clause every result record would have qty 33
If we have the where product "A" would have 3
product "B" would have qty 30.

How can I find all monitor purchases (not with monitor ID value, instead should use the term 'Monitor')

I have two tables,
I need to find all monitor purchases (but not with monitor ID, instead I should use 'Monitor'). I have made code, but it takes the quantity for all products, not only for 'Monitor'.
The code I made:
select name, Price,sum(quantity)
from Products, Orders
where name='Monitor'
How can I fix this problem?
You need to link the rows of both tables. Right now you are creating the cartesian product, containing every row from the first table combined with every row from the second table. With your screenshot, that's going to be 9 rows in total.
SELECT name, Price, SUM(quantity)
FROM Products, Orders
WHERE name='Monitor'
AND Products.ProductId = Orders.ProductId
Or use JOIN directly to separate the filter condition from the join condition:
SELECT name, Price, SUM(quantity)
FROM Products
INNER JOIN Orders
ON Products.ProductId = Orders.ProductId
WHERE Products.name='Monitor'

I think I'm calculating the total revenue from each warehouse wrong

I've got a question I'm working through and I'd like someone to double check my code because I'm trying to calculate the revenue for each warehouse in a database and the returning values seem high - it's returning tens of millions for most warehouses. Not impossibly high but high enough for me to take a second look.
Here is the ER diagram
And here is my code:
SELECT WAREHOUSES.WAREHOUSE_ID, WAREHOUSES.WAREHOUSE_NAME, SUM(ORDER_ITEMS.QUANTITY *
PRODUCTS.LIST_PRICE) AS TOTAL
FROM WAREHOUSES
JOIN INVENTORIES ON INVENTORIES.WAREHOUSE_ID = WAREHOUSES.WAREHOUSE_ID
JOIN PRODUCTS ON PRODUCTS.PRODUCT_ID = INVENTORIES.PRODUCT_ID
JOIN ORDER_ITEMS ON PRODUCTS.PRODUCT_ID = ORDER_ITEMS.PRODUCT_ID
GROUP BY WAREHOUSES.WAREHOUSE_NAME, WAREHOUSES.WAREHOUSE_ID
ORDER BY TOTAL DESC;
Is there something wrong with my SUM? I'm new to SQL so I'm sure you'll find plenty of tweaks to this code - and I'd love to hear about it!
Thank you!
You are calculating the total sales over all time for each product inside a warehouse. And then adding them up at the warehouse level.
I do not see that this is useful. And it is definitely overcounting sales.
I don't know what "revenue" means at the warehouse level. The data model doesn't seem to have any indication of which warehouse provided the products for a given order.
My best guess is that "revenue" means "potential revenue". That is, for all the products in inventory in the warehouse, how much revenue could be generated if they were sold at full price?
As a hint: This calculation has nothing to do with orders or orderlines. It only requires calculations between products and inventory.
The query looks OK, except I would think order_items.unit_price reflects the actual price paid and hence the sales revenue.
Here it is tidied up a little. I use aliases for the table names rather than repeating the whole name. Opinions vary on how to lay out SQL, and join clauses in particular, but this works better for me than a monolithic block of uppercase text.
select w.warehouse_id
, w.warehouse_name
, sum(oi.quantity * oi.unit_price) as total
from warehouses w
join inventories i on i.warehouse_id = w.warehouse_id
join products p on p.product_id = i.product_id
join order_items oi on p.product_id = oi.product_id
group by w.warehouse_name, w.warehouse_id
order by total desc;
You could check the results for one order, or one product, or one warehouse by including their ID in the select list and group by clauses and confirming that it gives the expected total. Sample data would help here.

Find item name along with the seller id and buyer id such that the seller has sold the item to the buyer

Hi IM trying to build a query for the following sentence for sql.
For each seller and each item sold by the seller, find the total amount sold.
I have 3 tables but not sure If i have to use them all. I have a feeling I need to use at least three tables to get this query but I keep getting an error. Also, I keep getting an error when I try to the following:
select selleruserid, itemid, sum(price) total
from sales_fact s
join items_dim i on i.itemid = s.itemid
join sellers_dim d on d.userid = s.selleruserid
group by selleruserid, itemid
I added a picture below of my tables.
All the information you want is in the fact table, so the other tables do not seem necessary:
select sf.selleruserid, sf.itemid, sum(sf.price) as total
from sales_fact s
group by sf.selleruserid, sf.itemid;
You would need to join in the other tables if you needed other information from the dimension, such as the name.

Creating an SQL query to list all clients, who spent over 1000$

So, I have three tables with the following rows: Customers (Customer_id and Name), Orders (Customer_id, Product_id, Quantity) and Products (Price).
How do I write a query which shows all customers who spent more than 1000$? Do I have to join the tables?
Because this is homework, I'm not going to give you the answer, just information on how to arrive at the answer.
You need to include the customers table, because that's what your looking for, customers. You'll need to join in aggregate with the orders table, so you can find out how many of each product they've ordered, and you'll need to join with the products table to find the prices of all those items in order to total them up to determine if they've spent more than $1000.
Go to it. Tell us how you get on.
SELECT * FROM customer c JOIN (
SELECT a.customer_id,SUM(a.quantity*b.price) spent FROM orders a
JOIN products b ON b.product_id=a.product_id GROUP BY a.customer_id
) d ON d.customer_id=c.customer_id WHERE d.spent>1000