我需要一个可以提供以下查询结果的查询:
select avg( salary) from company;
select avg(salary) from company where department="Development";
结果集应包含两列,一列是avg_company和avg_department。
智能解决方案对我有帮助
答案 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
个值。)