2014-10-06 100 views
1

我已经写了一个非常简单的查询来从我的数据库中返回具有未委托员工的所有部门,我应该在哪里查看数字了解如何显示有多少员工。显示从SELECT语句返回的结果数量作为列

对于〔实施例,我想:

Departments | Un-Commissioned Empl. 
---------------------------------- 
Admin.  |   7 
Marketing |   5 
Purchasing |   10 

enter image description here

回答

2

假设我正确理解你的模型,你需要join 2代表一起,使用count聚合得到退役员工:

select d.department_name, count(*) 
from departments d 
    inner join employees e on d.department_id = e.department_id 
where e.commission_pct = 0 
group by d.department_name 

如果需要,即使他们没有退役employeed各部门,你要使用outer join,而不是与移动地方标准的连接:

select d.department_name, count(e.employee_id) 
from departments d 
    left join employees e on d.department_id = e.department_id 
     and e.commission_pct = 0 
    group by d.department_name 
+0

不幸的是,当我尝试,我得到这个“专栏'departments.DEPARTMENT_NAME'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。“ – Kevin 2014-10-06 03:31:51

+0

@Kevin - 看到编辑,你只需要添加'group by'子句... – sgeddes 2014-10-06 03:32:35

+0

感谢一堆,现在我知道该怎么做了,有时间到w3school去学习如何去做。 – Kevin 2014-10-06 03:34:41