2017-02-25 94 views
0

我想寫一個SQL查詢返回一個表,該表包含表中僱傭至少一名員工的所有部門,他們僱用的人數以及每個部門的薪水總和,按部門ID責令編寫SQL查詢返回表

部門:

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 
+1

提示:'GROUP BY'。 'JOIN'甚至不是必需的。 –

回答

2

這僅僅是簡單的group by

select dept_id, 
    count(*) cnt, 
    sum(salary) sum_of_salary 
from employee 
group by dept_id 
order by dept_id; 
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 
+1

我們不需要連接來獲得原始問題中的確切輸出。 –

+0

同意,但他會想要部門的名字 –