如何使用count语句从sql server中的多个表中获取信息?

时间:2012-10-02 13:48:49

标签: sql sql-server sql-server-2008

如何使用包含Dept_idDept_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')

2 个答案:

答案 0 :(得分: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更改INNER JOIN

答案 1 :(得分: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
抱歉,这是我的头脑。忘记了小组。