有没有其他方法来编写此查询?

时间:2015-06-02 15:44:14

标签: sql oracle group-by

我的下表如下所示:

Table: Employee
1.empName
2.empNo
3.deptId

Table: Department
1.deptId
2.deptName

我需要找到“每个部门的员工姓名总数”:

我写了一个查询 -

Select count(*) as total, d.deptName, e.empName 
From Employee e 
     JOIN Department d on e.deptid = d.deptid
Group By d.deptName, e.empName;

以上查询工作正常,但我想学习如何编写查询以避免在e.empName子句中包含Group By,并仍然选择它?

有没有其他方法可以使用Oracle数据库来实现这一目标。

2 个答案:

答案 0 :(得分:2)

如果您需要找到"每个部门中员工姓名"的员工总数,那么您可以尝试使用Group BY子查询,然后使用Distinct加入员工表。

SAMPLE SQLFIDDLE

Select Distinct E.empName , t.deptName, total
FROM Employee E JOIN
                (Select count(*) as total, d.deptName, d.deptID
                From Employee e 
                   JOIN Department d on e.deptid = d.deptid
                Group By d.deptName, d.deptID) t
                ON E.deptID = t.deptID  

答案 1 :(得分:1)

如果确实想要,你可以使用两个相关的子查询和select distinct。我认为这会奏效:

select distinct e.name,
       (select d.deptname from department d where d.deptid = e.deptid) as deptname,
       (select count(*) from employee e2 where e2.deptid = e.deptid and e2.name = e.name) as total
from employee e;

我不是100%肯定会起作用(因为我通常不会将select distinct与相关子查询一起使用)。您可能需要这样做:

select e.name,
       (select d.deptname from department d where d.deptid = e.deptid) as deptname,
       (select count(*) from employee e2 where e2.deptid = e.deptid and e2.name = e.name) as total
from (select distinct e.name, e.deptid from employee e) e;