I have a table catalog and I should find the sids of suppliers who charge more for some part than the average cost of that part (averaged over all the suppliers who supply that part)
My solution is working, the only thing, that I have a problem with, is the way I want to represent it. I want to have one column in the result that is showing the cost that is averaged over all the suppliers who supply that part. This should be the result:
sid pid cost avg_cost
----- ----- ------ ----------
s1 p8 11.70 10.71
s2 p3 0.55 0.52
s3 p8 12.50 10.71
And this is my result:
sid pid cost
----- ----- ------
s1 p8 11.70
s2 p3 0.55
s3 p8 12.50
Here is what i have done:
SELECT DISTINCT c.sid, c.pid, c.cost
FROM catalog AS c
WHERE c.cost > (SELECT avg(c1.cost) AS avg_cost
FROM catalog c1
WHERE c1.pid=c.pid)
GROUP BY c.sid, c.pid, c.cost;
You could turn your subquery into a
JOIN
, so that its result is available in the outer query :PS : in your original query, you did not need a
GROUP BY
since, you did not use aggregate functions in the outer query. Also, based on your data it seems likely that you do not need theDISTINCT
functionality.