I have the following tables:
Product(maker, model, type)
PC(model, speed, ram, hd, price)
Laptop(model, speed, ram, hd, screen, price)
Printer(model, color, type, price)
I need to write a query that will return the average price of all products made by each maker, but only if that average is >= 200, in descending order by price.
I have tried 2 different methods and both get me very close but not exactly what I need:
(SELECT maker, AVG(price) as a
FROM Product NATURAL JOIN PC
WHERE price >= 200
GROUP BY maker)
UNION
(SELECT maker, AVG(price) as b
FROM Product NATURAL JOIN Laptop
WHERE price >= 200
GROUP BY maker)
UNION
(SELECT maker, AVG(price) as c
FROM Product NATURAL JOIN Printer
WHERE price >= 200
GROUP BY maker)
ORDER BY a;
The above gives me the average prices made by each maker for all the products they have made but it is all in one column so you cannot visually tell what product each average is linked to.
SELECT maker,
(SELECT AVG(price)
FROM PC
WHERE price >= 200) as 'Average Cost of PCs',
(SELECT AVG(price)
FROM Laptop
WHERE price >= 200
GROUP BY maker) as 'Average Cost of Laptops',
(SELECT AVG(price)
FROM Printer
WHERE price >= 200
GROUP BY maker) as 'Average Cost of Printers'
FROM Product
GROUP BY maker;
The above successfully gives each type of product its own column and also a column for all the makers, but it gives the average cost for all PCs, Printers, and Laptops in their respective columns instead of the average cost of each made by the maker it is parallel to.
Im not sure which one I am closer to the answer with but I've hit a wall and I'm not sure what to do. If I could get the first code to divide into different columns it would be correct. if I could get the second one to average correctly it would be right.
I am very new to Stack Overflow so I apologize if I did not ask this question in the correct format
natural join
. All you need to do is add a column that accidentally matches the name of a column in another table, and you've changed the join criteria of those two tables.