2017-10-17 35 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