You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写PostgreSQL查询返回员工数≤5的部门经理ID?

PostgreSQL查询:返回员工人数≤5的部门中经理的ID

需求

编写PostgreSQL查询语句,返回员工人数不超过5的部门中经理的ID。

employee数据表结构

  • id integer - 员工ID
  • name char - 员工姓名
  • department_id integer - 员工所属部门ID
  • chief_flg boolean - 员工是否为领导岗位的标识
  • birth_dt date - 出生日期
  • salary integer - 员工薪资

原始查询尝试

用户最初编写的查询语句如下,且认为可通过HAVING子句进行优化:

SELECT COUNT(e.id)<5, e.id as id_column
FROM employee AS e
WHERE chief_flg = 'True'
GROUP BY e.id

优化后的查询语句

SELECT e.id AS manager_id
FROM employee e
JOIN (
    -- 统计各部门员工数量,筛选出人数≤5的部门
    SELECT department_id
    FROM employee
    GROUP BY department_id
    HAVING COUNT(id) <= 5
) dept ON e.department_id = dept.department_id
WHERE e.chief_flg = TRUE;

优化思路说明

  1. 子查询部分:按department_id分组统计每个部门的员工总数,通过HAVING子句直接筛选出员工人数不超过5的部门ID;
  2. 主查询部分:将employee表与筛选后的部门数据关联,定位到这些部门中chief_flg为TRUE的员工(即经理),最终返回他们的ID。

注:PostgreSQL中布尔类型值直接使用TRUE/FALSE即可,无需加单引号。

内容的提问来源于stack exchange,提问作者adamantium

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 08:12:05