这道数据库到底怎么做?

查询年龄高于各自部门的平均年龄的职工信息,包括职工编号,姓名,性别,学历,所在部门,职级名称和年龄。

img

img


with t as (
    select a.department_id,avg(datediff(year,date_of_birth,getdate())) avg_age
    from tbl_departments a
    left join tbl_employees b on a.department_id=b.department_id
    group by a.department_id
)
select * from tbl_employees a
left join t b on a.department_id=b.department_id
where datediff(year,date_of_birth,getdate())>avg_age

使用with as子查询先统计每部门的平均年龄,然后关联这个子查询结果找出高于平均年龄的记录。
具体写法可以参考这篇文章:https://blog.csdn.net/jerbo/article/details/130024165