查询每个部门工资最高的员工

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;

猜你喜欢

转载自blog.csdn.net/tangerine_/article/details/86000226