2017-10-17 37 views
0

我正在为有三个表(教授,薪酬和部门)的任务工作。试图编写一个使用三个表和AVG()函数的SQL查询

我需要编写一个查询,按部门输出平均休假天数。

的表和模式是表如下:

sqlite> .schema compensation 
CREATE TABLE compensation (id integer, professor_id integer, salary integer, 
vacation_days integer); 
sqlite> SELECT * FROM compensation; 
id   professor_id salary  vacation_days 
---------- ------------ ---------- ------------- 
1   1    64000  2    
2   2    35000  8    
3   3    56750  10   
4   4    42950  8    
5   5    30000  4    
6   6    102750  22  

sqlite> .schema department 
CREATE TABLE department (id integer, department_name text); 
sqlite> SELECT * FROM department; 
id   department_name 
---------- --------------- 
31   Transfiguration 
32   Defence Against 
33   Flying   
34   Study of Ancien 
35   Care of Magical 

sqlite> .schema professor 
CREATE TABLE professor (id integer, professor text, department_id integer); 
sqlite> SELECT * FROM professor; 
id   professor   department_id 
---------- ---------------- ------------- 
1   Albus Dumbledore 31   
2   Severus Snape  32   
3   Dolores Umbridge 32   
4   Bathsheda Babbli 34   
5   Rubeus Hagrid  35   
6   Wilhelmina Grubb 35   

理想的情况下,这是我的查询将会导致什么...

department_name    average_vacation_days 
----------------------------- --------------------- 
Transfiguration    2.0 
Defence Against the Dark Arts 9.0 
Study of Ancient Runes   8.0 
Care of Magical Creatures  13.0 

回答

1

这只是需要一个直加盟的三个表按部门汇总。请注意,如果给定部门没有人数,我会在COALESCE中将平均值包括在内。请尝试以下查询:

SELECT 
    d.department_name, 
    COALESCE(AVG(c.vacation_days), 0) AS average_vacation_days 
FROM department d 
LEFT JOIN professor p 
    ON d.id = p.department_id 
LEFT JOIN compensation c 
    ON p.id = c.professor_id 
GROUP BY 
    d.id, 
    d.department_name