查找在经理手下工作的员工人数

Find the number of employees working under a manager

我有三个表,分别是 branch、employee 和 manager,结构如下

Table: branch
CREATE TABLE branch (
    id            INTEGER PRIMARY KEY AUTOINCREMENT
                          NOT NULL
                          UNIQUE,
    name          FLOAT,
    city          VARCHAR,
    region        VARCHAR,
    postal_code   VARCHAR,
    street        VARCHAR,
    street_number VARCHAR
);

Table: employee
CREATE TABLE employee (
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
    surname       VARCHAR,
    name          VARCHAR,
    branch_id     INTEGER REFERENCES BRANCH (ID),
    city          VARCHAR,
    region        VARCHAR,
    street        VARCHAR,
    street_number VARCHAR,
    phone         VARCHAR,
    mobile        VARCHAR,
    vat           VARCHAR,
    amka          VARCHAR,
    at            VARCHAR
);


Table: manager
CREATE TABLE manager (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    employee_id INTEGER REFERENCES employee (id) 
                        UNIQUE
                        NOT NULL
);

我想这样查看每个经理的id和他手下的员工数量

Manager   Number of employees


   1         5
   2        13

到目前为止我已经做了这个,显示了每个经理在哪个分支工作,但我不知道如何继续计数。

SELECT manager.id AS [Manager id],
       employee.name AS [Manager name],
       branch.name AS [Branch name],
       branch.id AS [Branch id]
  FROM (
           (
               manager
               INNER JOIN
               employee ON manager.employee_id = employee.id
           )
           INNER JOIN
           branch ON employee.branch_id = branch.id
       );

我想到的解决方案是首先找到每个经理在哪个分支机构工作,然后计算该分支机构的所有员工减去一个(经理)。问题是我不知道如何在 sql.

中准确表达它
select manager.id as manager, count(employee_id) as 'Number of Empolyee' 
from manager
group by manager.id

COUNT 将导致员工计数 w.r.t 经理 GROUP BY,因为该经理下的员工 manager_id 和 employee_id 保存在同一个 table.

如果经理table只保存经理的数据,那么员工table也应该有manager_id,就像它有branch_id一样,这样我们就知道哪个员工在哪个经理手下工作。在这种情况下创建员工和经理关系

select `manager.id` as manager, count(employee.employee_id) as 'Number of Empolyee' 
from manager join employee on emplyee.manager_id=manager.id
group by `manager.id`

由于每个分支机构只能有一名经理,您可以统计一个分支机构的员工人数,然后将经理加入他们的分支机构。从那里您可以计算每个分支机构的员工人数。

SELECT manager.id               AS manager_id,
       manager_employee.name    AS manager_name,
       COUNT(employee.id) - 1   AS employee_count
  FROM manager
 INNER JOIN employee AS manager_employee
    ON manager.employee_id = manager_employee.id
 INNER JOIN branch
    ON manager_employee.branch_id = branch.id
 INNER JOIN employee
    ON branch.id = employee.branch_id
 GROUP BY manager.id,
          manager_employee.name