使用count,SQL查询进行子选择

时间:2015-05-09 19:28:41

标签: mysql sql

您好我需要选择所有女性工作者的工资和工资,其中至少有两名男性,其工资与女性相同......

这是表格

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

这是我的代码,在某种程度上,这个剂量给出了所需的结果

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);

2 个答案:

答案 0 :(得分:1)

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 :(得分:0)

有几种方法可以做到这一点。以下是使用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)