选择特定信息

时间:2013-12-09 15:19:57

标签: sql database oracle

我的表格结构如下(表格中有更多值,但我只写了与此相关的值):

Department(dep_id, dep_name)  
Employee(dep_id)  

我需要显示dep_name和每个部门的员工数量,除了特定部门(我们称之为DepX)和只有多个员工的部门。 我尝试了多种方法来解决这个问题,但没有一种方法可行。 我试过的一些方法:

SELECT department.dep_name, COUNT(employee.dep_id) AS NumberOfEmployees FROM employee
INNER JOIN department ON employee.dep_id=department.dep_id
WHERE dep_name<>'DepX'
GROUP BY dep_id
HAVING COUNT(employee.dep_id) > 1;

SELECT dep_name FROM department
WHERE dep_name <>'DepX'
UNION
SELECT COUNT(*) FROM employee
WHERE COUNT(*) > 1
GROUP BY dep_id;

我无法弄清楚这一点。谢谢!

3 个答案:

答案 0 :(得分:1)

SELECT department.dep_name, COUNT(employee.dep_id) AS NumberOfEmployees FROM employee
INNER JOIN department ON employee.dep_id=department.dep_id
WHERE department.dep_name not in('DepX')
GROUP BY department.dep_name
HAVING COUNT(employee.dep_id) > 1;

根据您的需要更新您的表别名

答案 1 :(得分:1)

第一个示例现在可以正常工作,因为您在结果中包含dep_name而没有聚合但没有对其进行分组。

您可以在分组中使用部门名称而不是ID:

SELECT department.dep_name, COUNT(employee.dep_id) AS NumberOfEmployees FROM employee
INNER JOIN department ON employee.dep_id=department.dep_id
WHERE dep_name<>'DepX'
GROUP BY department.dep_name
HAVING COUNT(employee.dep_id) > 1;

或在子查询中执行COUNT

SELECT department.dep_name, 
       e.NumberOfEmployees 
FROM department
INNER JOIN (SELECT dep_id, 
                   COUNT(*) NumberOfEmployees 
            FROM employee
            GROUP BY dept_id
            HAVING COUNT(dept_id) > 1    
           ) e
ON department.dep_id = e.dep_id
WHERE dep_name<>'DepX'

答案 2 :(得分:0)

测试这个。此查询不仅可以帮助您返回dept_name,还可以根据需要返回Department中的所有字段:

SELECT d.*, A.numOfEmployees
FROM Department d,
     (
    SELECT e.dep_id, COUNT(*) numOfEmployees
    FROM Employee e
    GROUP BY e.dep_id
    HAVING COUNT(*) > 1
     ) A
WHERE d.dep_id = A.dep_id
AND d.dep_name != 'DepX'