1. 程式人生 > >查詢每個部門工資最高的員工

查詢每個部門工資最高的員工

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id唯一標識 /注:自增',
  `name` varchar(50) DEFAULT NULL COMMENT '名稱',
  `salary` int(11) DEFAULT NULL COMMENT '薪水',
  `departmentId` varchar(50) DEFAULT NULL COMMENT 'ID',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='員工表';
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id唯一標識 /注:自增',
  `name` varchar(50) DEFAULT NULL COMMENT '部門名稱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='部門表';

insert into employee (id,name,salary,departmentId) value (1,'Joe',70000,'1');
insert into employee (id,name,salary,departmentId) value (2,'Henry',80000,'2');
insert into employee (id,name,salary,departmentId) value (3,'sam',60000,'2');
insert into employee (id,name,salary,departmentId) value (4,'max',90000,'1');
insert into department (id,name) value (1,'IT');
insert into department (id,name) value (2,'Sales');
select d.Name as department,e.Name as employee,Salary
from employee e join department d on e.departmentId=d.Id
where (e.Salary,e.departmentId) in (select max(Salary),departmentId from employee group by departmentId);

select d.Name as department,e.Name as employee,e.salary
from department d,employee e
where e.departmentId=d.id and e.salary=(Select max(salary) from employee where departmentId=d.id);


select salary,departmentId from employee order by departmentId;#按DepartmentId排序查詢

select max(salary),departmentId from employee group by departmentId;#按DepartmentId分組查詢

#查詢每個部門的員工工資總和
select sum(salary),departmentId from employee group by departmentId;