Subselect with score, SQL query

Hi, I need to choose empno and the salary of all female workers who have at least two men in their department with the same salary as the woman ..

These are tables

EMP:
empno|ename|deptno|sal|gender   
DEPT:
deptno|dname

This is my code, for some reason this associate gives the desired result

SELECT *
FROM EMP E
WHERE E.GENDER = 'F' AND 2 <= (SELECT COUNT(*)
                               FROM EMP E2
                               WHERE E2.GENDER = 'M' AND
                               E2.SAL = E.SAL
                               AND E.DEPTNO = E2.DEPTNO);
+4
source share
2 answers

There are several ways to do this. Here is one parameter with exists:

select empno, sal
from emp e
where gender = 'F'
and exists (
  select 1
  from emp e2 
  where e2.gender = 'M' 
    and e.sal = e2.sal and e.deptno = e2.deptno
  having count(*) > 1)
0
source
select e1.* 
from emp e1
join
(
    select sal, deptno
    from emp
    group by sal, deptno
    having count(distinct gender) = 2
    and sum(gender = 'M') >= 2
) e2 on e1.sal = e2.sal and e1.deptno = e2.deptno
where e1.gender = 'F'

SQLFiddle demo

+1
source

All Articles