我可以获得员工人数和平均工资,但是当我尝试获得列出低于平均工资的员工人数的附加选择时,它失败了。
select count(employee_id),avg(salary)
from employees
Where salary < avg(salary);
我可以获得员工人数和平均工资,但是当我尝试获得列出低于平均工资的员工人数的附加选择时,它失败了。
select count(employee_id),avg(salary)
from employees
Where salary < avg(salary);
问题是这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
select count(*), (select avg(salary) from employees)
from employees
where salary < (select avg(salary) from employees);
不清楚您希望在结果集中包含哪些列,这使得您很难回答您的问题。使问题清晰可提高答案的质量。
你似乎想要 3 个事实:
并且您显示了一个查询,该查询完成了前两个事实的工作:
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
在很多情况下,这样写子查询是不合适的,但是对于指定查询的解释,就可以了。
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
Note: I used a LEFT join so if you had 3 equal employees, it would show 0 instead of no results (nobody below below average).
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
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);