1

如何使用带有字段的计数函数查询每个部门的员工人数,Dept_id使用下面的数据结构?Dept_nameNumber of employees

create database Emp_det

create table Dept
(
    Dept_ID int not null primary key,
    Dept_name varchar(255)
)

create table Emp_table
(
    Emp_no int not null primary key,
    Emp_name varchar(255) not null,
    Dept_ID int foreign key references Dept(Dept_ID),
    Emp_status varchar(255)
)

create table Salary_table
(
    Emp_no int not null foreign key references Emp_table(Emp_no),
    From_date datetime,
    End_date datetime,
    Basic int,
    HRA int,
    Others int,
    Total int,
    Emp_status varchar(255),

    constraint pk_emp_det primary key (emp_no,From_date)
);

insert into Dept
values(10, 'I.T'), (11, 'H.R'),(12, 'Procurement'),(13, 'QS');

insert into Emp_table
values(1111,'Manivannan','10','A'),
(1222,'Faizal','10','A'),
(4122,'Marzook','10','A'),
(1223,'Venu','11','A');

insert into Salary_table
values(1111,'01/09/2012','1/10/2012',10000,10000,2000,22000,'A'),
(1222,'01/09/2012','1/10/2012',5000,5000,1000,11000,'A'),
(4122,'01/09/2012','1/10/2012',1000,1000,5000,2500,'A'),
(1223,'01/09/2012','1/10/2012',10000,10000,2000,22000,'A')
4

2 回答 2

4
SELECT D.Dept_ID, D.Dept_Name, COUNT(*) NumberOfEmployees
FROM Dept D
LEFT JOIN dbo.Emp_Table ET
ON D.Dept_ID = ET.Dept_ID 
GROUP BY D.Dept_ID, D.Dept_Name

这将列出所有部门,即使没有员工。如果您只想要有员工的部门,您可以LEFT JOIN用 an更改。INNER JOIN

于 2012-10-02T13:55:21.480 回答
1
    select 
      Dept_id, Dept_name,count(distinct Emp_no) as Number_of_employees
    from 
      Dept d inner join
      Emp_table e on 
      d.Dept_ID = e.Dept_ID
    group by
      Dept_id, Dept_name

抱歉,这不是我的想法。忘记组了。

于 2012-10-02T13:54:41.900 回答