I have 2 tables, ‘manufacturers’ and ‘products’. A manufacturer can have multiple products and a product has a ‘qty’, ‘price’ and ‘cost’ field.
I’ve LEFT JOINed them together and can get SUMs on the ‘price’ and ‘cost’ fields based on multiplying by ‘qty’ but I’d like to get a ‘cost_complete’ flag set to false if ANY of the product.cost fields from a specific manufacturer are not set, thus allowing me to identify any manufacturer who has products that don’t yet have a ‘cost’ set.
This is what I have so far, but I think that my ‘cost_complete’ flag gets overwritten for each product.
SELECT m.name, p.quantity, p.price, p.cost, SUM(p.quantity) AS total_quantity,
SUM(p.price*p.quantity) AS total_price, SUM(p.cost*p.quantity) AS total_cost,
IF(p.cost<0, 'true','false') AS cost_complete
FROM manufacturer m
LEFT JOIN product p ON m.manufacturer_id = p.manufacturer_id
GROUP BY m.manufacturer_id
ORDER by m.name
2
Answers
You can do a conditional sum in case the p.cost is null (or is lower than 0 as you have in your code). Then you will have the number of products that donยดt have a p.cost (if it is 0, all products have a cost)
To query a list of manufacturers who have at least one product that has no cost set, this query should do.
I’d like to imagine what this query does as follows:
total_quantity
),total_price
),total_cost
), andmin_cost
).min_cost
) is zero.Notice how I removed
p.quantity
,p.price
, andp.cost
from theSELECT
statement. This is because we used theSELECT
statement to aggregate a summary about a list of products under a manufacturer; there’s no picking a single product. In short, it won’t make sense to include them anymore as there could be more than one product under the same manufacturer that have nocost
set.