尝试编写一个使用三个表和AVG()函数

时间:2017-10-17 07:35:25

标签: sql sqlite

我正在完成一项有三个表(教授,薪酬和部门)的任务。

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

表的表和架构如下:

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 个答案:

答案 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