找出每个办公室的员工人数 - Mysql

时间:2017-01-13 20:39:53

标签: mysql sql database

我正在尝试显示每个办公室有多少员工以及办公室名称,但我无法让它工作。我试过这个

select count(*) as count,office_staff.staff_id
from staff
inner join office_staff on staff.staff_id = office_staff.staff_id
group by staff.staff_id 

但我得到的输出是:

# count, staff_id
'1', '1001'
'1', '1002'
'1', '1003'
'1', '1004'
'1', '1005'
'1', '1006'

-- -----------------------------------------------------
-- Table `mydb`.`staff`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`staff` (
  `staff_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `office_id` INT(10) UNSIGNED NOT NULL,



-- -----------------------------------------------------
-- Table `mydb`.`office_staff`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`office_staff` (
  `office_staff_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `staff_id` INT(10) UNSIGNED NOT NULL,
  `office_id` INT(10) UNSIGNED NOT NULL,
  `


-- -----------------------------------------------------
-- Table `mydb`.`offices`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`offices` (
  `office_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `address_id` INT(10) UNSIGNED NOT NULL,

任何人都可以帮助我吗?谢谢!

3 个答案:

答案 0 :(得分:0)

使用office id而不是staff_id

  select count(*) as count, office_staff.office_id
  from staff
  inner join office_staff on staff.staff_id = office_staff.staff_id
  group by office_staff.office_id

答案 1 :(得分:0)

我假设您的offices表格中有一列名为Name(您的结构已被切断)。我拉Name的原因是因为这一行:

  

我正在尝试显示每个办公室有多少员工以及办公室名称

这应该是您需要做的所有事情(根据需要更改列名称):

Select  O.Name   As OfficeName,
        Count(*) As count
From    staff        S
Join    office_staff OS On S.staff_id = OS.staff_id
Join    office       O  On O.Office_Id = OS.Office_Id
Group By O.Name

答案 2 :(得分:0)

尝试:

select count(*) as count,office_id
from staff, office_staff
inner join office_staff on staff.staff_id = office_staff.staff_id
group by office.id