a.ymous
a.ymous

Reputation: 139

SQL Query Trouble (with constraint)

I have a problem with a query I am running. I want to display the Empcode, Empname and postcode of all employees who satisfy the following: every stock item they sell has a price value above the average of all stock items.

So here is my query:

select distinct SU.empCode, SU.empName, SU.PostCode
from Suppliers SU, Stocks ST
where ST.Price >= (select AVG(Price) from Stocks ST)

I get all the employees back ( 6 in total ) but the correct answer is 2 employees. Does anybody know what I'm doing wrong?

Any help would be appreciated, thanks.

Upvotes: 0

Views: 32

Answers (1)

DazzaL
DazzaL

Reputation: 21993

this should work

select empCode, empName, PostCode
  from (select SU.empCode, SU.empName, SU.PostCode, min(st.Price) over (partition by su.empcode) min_price,
               avg(st.price) over () avg_price
          from Suppliers SU, Stocks ST
         where SU.empcode = ST.empcode)
 where min_price > avg_price;

Upvotes: 1

Related Questions