鉴于数据库设计类似于以下内容:
EMPLOYEE: ID, Gender, Salary, Dno
以下SQL是否有效用于返回没有女性工作的男性和部门编号?
SELECT males, dno FROM
(SELECT COUNT(Gender = 'male') AS males, COUNT(Gender = 'female') AS females, Dno
FROM EMPLOYEE
GROUP BY Dno)
WHERE females = 0;
我不确定我是否在此示例中正确使用COUNT。
答案 0 :(得分:3)
您可以尝试此查询:
SELECT DNO, SUM(CASE WHEN GENDER = 'male' THEN 1 ELSE 0 END) AS MALE
FROM EMPLOYEE
GROUP BY DNO
HAVING SUM(CASE WHEN GENDER = 'female' THEN 1 ELSE 0) = 0;
计算每个部门的男性和女性员工人数,然后选择女性人数为0的那些;
答案 1 :(得分:3)
假设人们只是男性或女性,这可能是最简单的解决方案:
SELECT Dno, COUNT(*)
FROM EMPLOYEE
GROUP BY Dno
HAVING SUM(gender = 'female') = 0;
count(*)
返回男性人数。如果没有女性,那么每个人都是男性 - 因此完全统计。
你可以通过
更加明确SELECT Dno, SUM(gender = 'male')
FROM EMPLOYEE
GROUP BY Dno
HAVING SUM(gender = 'female') = 0;
编辑:
问题中的示例代码与Oracle标记不一致(当我最初回答时,我认为这不是问题所在)。假设只有两种性别,那么Oracle中最简单的方法是:
SELECT Dno, COUNT(*)
FROM EMPLOYEE
GROUP BY Dno
HAVING MIN(gender) = 'male';
顺便提一下,这是ANSI标准语法,可以在任何数据库中使用。
答案 2 :(得分:1)
试试这个:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
或许这样的事情可以得到更全面的画面:
select dno, count(*) as non_female_staff
from employee
group by dno
having count(case when gender = 'female' then 1 end) = 0;
DNO NON_FEMALE_STAFF
---------- ----------------
3 6