SQL:查询以获取公司的平均工资和部门的平均值

时间:2017-10-15 14:31:56

标签: mysql sql

我需要一个可以提供以下查询结果的查询:

select avg( salary) from company;
select avg(salary) from company where department="Development";

结果集应包含两列,一列是avg_company和avg_department。

智能解决方案对我有帮助

2 个答案:

答案 0 :(得分:1)

一个简单的方法是两个子查询:

select (select avg(salary) from company) as overall_avg,
       (select avg(salary) from company where department = 'Development') as department_avg;

另一个是条件聚合:

select avg(salary) as overall_avg,
       avg(case when department = 'Development' then salary end) as development_avg
from company;

这样做的好处是只扫描一次表。

答案 1 :(得分:1)

使用条件聚合:

SELECT
    AVG(salary) AS total_avg,
    AVG(CASE WHEN department = 'Development' THEN salary END) AS dvpmnt_avg
FROM yourTable;

AVG表达式CASE的工作原因是,与开发部门对应的任何薪水都会被计为NULL,因此会被忽略(MySQL的AVG函数忽略NULL个值。)