Get employees which have smaller salary than any of those who sold more than one order

masteroscar :

Sorry for long title but I wanted to explain the situation.

My brains are almost exploding I have tried this for five hours now, and I don't get it. Got just a big headache.

I want to get those employees which haec smaller salary than anyone of those who has sold one or more orders. There is two tables EMPLOYEES and ORDERS.

EMPLOYEES have these columns; First name, Last name, Social security number, Salary.

ORDERS have these columns; Social security number, OrderID

This is best solution so far.

SELECT H.SOCSECNUM, H.LASTNAME, H.FIRSTNAME, H.SALARY
FROM EMPLOYEES H
WHERE H.SALARY < ALL(SELECT COUNT(T.ORDERID)
                     FROM ORDERS T
                     WHERE  H.SOCSECNUM = T.SOCSECNUM
                     HAVING COUNT(T.ORDERID) > 0
                     );

I understand this like get social security number, name and salary of all employees which have smaller salary than anyone who sold more than 0 orders.

Am I stupid or what is wrong in that? Now this prints all employees which have 0 orders. If i change 0 -> 1 it prints all employees which have one or less orders.

GMB :

I think that's the query you wanted to write:

select e.*
from employees e
where h.salary < all (
    select h1.salary
    from employees e1
    where exists (select 1 from orders o1 where o1.socsecnum = e1.socsecnum)
)

The subquery returns the list of salaries of employees that performed at least one sale. You can then use all to filter the table against that.

You could also use aggregation:

select e.*
from employees e
where h.salary < (
    select min(h1.salary)
    from employees e1
    where exists (select 1 from orders o1 where o1.socsecnum = e1.socsecnum)
)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=376862&siteId=1