编写SQL查询以返回表

时间:2017-02-25 15:42:15

标签: mysql sql

我想编写一个SQL查询,返回一个表,其中包含表中雇用至少一名员工的所有部门,他们雇用的人数以及每个部门的工资总额,按部门ID排序

部门:

dept_id | dept_name | dept_location
10      | Accounts  | Delhi  
20      | Marketing | Delhi 
40      | IT        | Warsaw 
30      | production| Hyderabad 
5O      | Sales     | Bengaluru

员工:

emp_id  | emp_name  | dept_id   | salary
1       | Jojo      |   20      | 5000
2       | Popat Lal |   30      | 15000
3       | Santa Singh|  40      | 25000
4       | Banta Singh|  20      | 7500
5       | Soban Lal |   20      | 15000
6       | Kk        |   10      | 12000
7       | Bob       |   20      | 35000
8       | John      |   30      | 25000
9       | Smith     |   40      | 5000

查询应返回:

dept_id | count     | sum_of_salary
10      | 1         | 12000
20      | 4         | 62500 
30      | 2         | 40000 
40      | 2         | 30000

2 个答案:

答案 0 :(得分:2)

这很简单group by

select dept_id,
    count(*) cnt,
    sum(salary) sum_of_salary
from employee
group by dept_id
order by dept_id;

答案 1 :(得分:1)

select d.dept_id, d.dept_name, count(*) total_hires, sum(salary) total_salary
from employee e join department d on e.dept_id = d.dept_id
group by d.dept_id, d.dept_name