表,Employee有EmployeeID,Salary列。 如何找到工资大于平均工资的EmployeeID?
使用子查询:
SELECT EmployeeID
FROM Employee
WHERE Salary > (SELECT AVG(Salary)
FROM Employee);
是否可以使用连接? 还有其他方法吗?
答案 0 :(得分:6)
以这种方式编写它似乎很愚蠢,但这里没有任何子查询:
SELECT a.EmployeeID
FROM Employee a
CROSS JOIN Employee b
GROUP BY a.EmployeeID, a.Salary
HAVING a.Salary > AVG(b.Salary)
答案 1 :(得分:3)
/r/n
将平均工资计算移至FROM以计算一次。 BTW大多数现代数据库可以优化您的查询以计算一次。
答案 2 :(得分:1)
SELECT * from
(SELECT EmployeeID,salary AVG(salary) OVER() avg_salary FROM Employee)
WHERE Salary >avg_salary
答案 3 :(得分:0)
SELECT e.EmployeeID FROM Employee e
JOIN
(
SELECT avg(Salary) as Salary FROM Employee
) e1
ON e.Salary > e1.Salary
答案 4 :(得分:0)
Declare @AverageSalary as Money
Select @AverageSalary = AVG(Salary) From Employee
Select * from Employee Where Salary > @AverageSalary