如何让所有员工的薪水低于平均工资?

时间:2012-12-10 20:33:18

标签: sql

我可以得到员工的数量和平均工资,但是当我试图获得额外的选择列表时,支付的员工数量低于平均水平就失败了。

select count(employee_id),avg(salary) 
from employees
Where salary < avg(salary);

6 个答案:

答案 0 :(得分:3)

select count(*), (select avg(salary) from employees)
from employees 
where salary < (select avg(salary) from employees);

答案 1 :(得分:1)

   select TotalNumberOfEmployees,
          AverageSalary,
          count(e.employee_id) NumberOfEmployeesBelowAverageSalary
     from (
            select count(employee_id) TotalNumberOfEmployees,
                   avg(salary) AverageSalary
              from employees
          ) preagg
left join employees e on e.salary < preagg.AverageSalary
 group by TotalNumberOfEmployees,
          AverageSalary

注意:我使用了LEFT加入,所以如果你有3个相同的员工,它会显示0而不是没有结果(没有人低于平均水平)。

答案 2 :(得分:1)

问题是AVG是一个聚合函数。 SQL不够聪明,无法弄清楚如何在行中混合聚合结果。传统方式是使用连接:

select count(*), avg(e.salary),
        sum(case when e.salary < const.AvgSalary then 1 else 0 end) as NumBelowAverage
from employees e cross join
     (select avg(salary) as AvgSalary from employees) as const

答案 3 :(得分:1)

目前尚不清楚结果集中需要哪些列,这使得难以回答您的问题。明确问题可以提高答案的质量。

你似乎想要3个事实:

  1. 员工人数。
  2. 平均工资。
  3. 收入低于平均工资的员工人数。
  4. 并显示一个查询,它可以完成前两个事实的工作:

    SELECT COUNT(*) AS NumberOfEmployees,
           AVG(Salary) AS AverageSalary
      FROM Employees
    

    COUNT(*)COUNT(Employee_ID)之间有什么区别?区别在于后者仅计算Employee_ID列中存在非NULL值的行。一个好的优化器会识别出Employee_ID是一个主键并且不包含NULL值,并且查询将是相同的。但COUNT(*)更常规,更不依赖于优化器。

    可以通过子查询在选择列表中生成另一个统计信息作为简单值:

    SELECT COUNT(*) AS NumberOfEmployees,
           AVG(Salary) AS AverageSalary,
           (SELECT COUNT(*)
              FROM Employees
             WHERE Salary < (SELECT AVG(Salary) FROM Employees)
           ) AS NumberOfEmployeesPaidSubAverageWages
      FROM Employees
    

    在许多情况下,编写类似的子查询是不合适的,但是对于指定查询的解释,它很好。

答案 4 :(得分:0)

select * from <table name> where salary < (select avg(<salary column name) from <table name>);

示例:

select * from EMPLOYEE where sal < (select avg(emp_sal) from EMPLOYEE);

答案 5 :(得分:0)

SELECT e.ename,e.deptno,e.sal,d.avg
FROM emp e,(SELECT deptno, avg(sal) avg
             FROM emp
             GROUP BY deptno) d
 WHERE e.deptno=d.deptno
 AND
 e.sal < d.avg