Cost per box is in the table named products whereas no of boxes is in sales table. PID is common in both tables both are in same schema and database. I want total cost of boxes per PID shown against PID(product id). PID is the primary key.
I was trying this but it didn’t work as a syntax
SELECT s.PID, pr.Boxes, (s.Boxes*pr.Cost_per_box) AS Total_Cost_of_Boxes
join products pr
on pr.PID = s.PID;
I am a beginner so pardon anything silly in the syntax and please provide me the right syntax. One more thing pr.cost_per_box is FLOAT and s.Boxes is NUMERIC. pr. represents products table and s. represents sales table. And I have passed syntaxes before hand SELECT * from sales; and SELECT * from products; .
SELECT s.PID, pr.Boxes, (s.Boxes*pr.Cost_per_box) as Total_Cost_of_Boxes
join products pr
on pr.PID = s.PID;
was expecting what I mentioned in details.
PID | BOXES | TOTAL COST OF BOXES
2
Answers
Create tables
then add data
now you select data with joins, remember use "from"
result
You have a
sales
and aproduct
table and you need to join the two. Yet, in your query, you forgot to specify that you want to selectfrom sales s join products p ...
, you only added thejoin
part, but not thefrom
and you had the syntax error problem you reported, but it is expected if you have ajoin
without afrom
in your select.So here’s a better query:
Explanation:
products
, rather than fromsales
, as we can be sure that there are no sales withoutproducts
, so it’s better to haveproducts
as the point of departuresales
on matchingPID
values, so for eachproducts
we will either have one or more actualsales
record, or an allnull
sales
record representing the nonexistentsales
of a product that was not sold yet so farproducts
fields so each record will represent a product with itssales
dataBoxes
ofsales
to see how many boxes were sold andcoalesce
it to 0 if there are nosales
records for the product