-1

以下是关系:

CREATE TABLE employee (
  name    varchar2(15) not null, 
  ssn      char(9),
  sex      char,
  salary   number(10,2),
  dno      number(4),
  primary key (ssn),
  foreign key (dno) references department(dnumber)
);

CREATE TABLE department (
  dname        varchar2(15) not null,
  dnumber      number(4),
  primary key (dnumber),
  unique (dname),
);

Q1:对于每个员工平均工资超过 30,000 美元的部门,检索部门名称和为该部门工作的员工人数。

Q2:假设我们想要每个部门的男性员工数量而不是所有员工(如 Q1)来计算部门平均值和员工数量。我们可以在 SQL 中指定这个查询吗?为什么或者为什么不。

谢谢!

4

3 回答 3

1

您的第一个查询可能看起来像

SELECT d.dname,
       COUNT(*) total_employees
  FROM department d LEFT JOIN
       employee e ON d.dnumber = e.dno
 GROUP BY d.dname
HAVING AVG(e.salary) > 30000;

而第二个

SELECT d.dname,
       COUNT(*) male_employees
  FROM department d LEFT JOIN
       employee e ON d.dnumber = e.dno
 WHERE e.sex = 'M'
 GROUP BY d.dname
HAVING AVG(e.salary) > 30000;

SQLFiddle

于 2013-04-10T20:31:38.453 回答
0

如果你想在一个 SQL 中获取所有员工的数量和男性员工的数量,你可以试试这个。

SELECT B.DNAME,
COUNT(*) AS TOTAL_EMPLOYEES,
COUNT(CASE WHEN A.SEX='M' THEN A.SEX END) AS MALE_EMPLOYEES,
AVG(A.SAL) AS ALL_AVG,
AVG(CASE WHEN A.SEX='M' THEN A.SAL END) AS MALE_AVG
FROM EMPLOYEE A JOIN DEPARTMENT B
ON A.DNO=B.DNUMBER
GROUP BY B.DNAME
于 2013-04-11T01:37:54.377 回答
0
SELECT dname, COUNT(*) AS Num_of_Employees    
FROM   employee, department    
WHERE  dno = dnumber AND EXISTS (
       SELECT AVG(Salary)    
       FROM   employee    
       GROUP BY dno    
       HAVING AVG(Salary)>30000)    
GROUP BY dname;    
于 2014-12-09T21:06:32.707 回答