【问题标题】:SQL: department name with minimum of 10 employeesSQL:至少有 10 名员工的部门名称
【发布时间】:2017-10-23 03:42:55
【问题描述】:

我有一张员工表和一个部门名称表。 结构是

员工 - 员工ID - 员工姓名 - 部门ID

部门 - 部门 ID - 部门名称

我想显示一个包含 10 名以上员工工作的部门名称的表格。

我试过没有结果的查询是:

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

请指正

【问题讨论】:

  • 您想要“最少 10 名员工”还是“超过 10 名员工”?

标签: mysql sql


【解决方案1】:

在 group by 之后有一个特定的子句,HAVING 子句,允许过滤聚合值。

select count(*) as count,d.department_name
from employees e
inner join departments d on e.department_id = d.department_id 
group by d.department_name
HAVING count(*) > 10

注意:where 子句应继续用于不依赖于聚合的条件。例如如果您只是想要“销售相关”部门

select count(*) as count,d.department_name
from employees e
inner join departments d on e.department_id = d.department_id 
WHERE d.department_name like 'sales%'
group by d.department_name
HAVING count(*) > 10

【讨论】:

  • 有一个约定,即施加 where 条件的表首先出现在选择中。我想这不是规则,只是一种传统。
  • @Strawberry 我当时正在使用手机,要整理到那种程度实在是太难了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2021-09-09
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多