sql查询某个条件

时间:2014-12-06 07:21:15

标签: mysql sql sql-server-2008 select group-by

我有一张表:

empId empSalary empDept
1   45000   IT
2   40000   IT
3   50000   SALES
4   60000   SALES
5   75000   IT
6   80000   IT
7   25000   OPS
8   30000   OPS
9   55000   MARKETING
10  60000   MARKETING

我必须写一个查询:

select empId where empSalary  > avg(empSalary) for each  empDept

请帮助。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT e.empId, e.empSalary, e.empDept  
FROM employee e 
INNER JOIN (SELECT e1.empDept, AVG(e1.empSalary) empSalary 
            FROM employee e1 
            GROUP BY e1.empDept
           ) a ON e.empDept = a.empDept AND e.empSalary > a.empSalary;

修改

SELECT e.empDept, COUNT(DISTINCT e.empid) noOfEmployees
FROM employee e 
INNER JOIN (SELECT AVG(e1.empSalary) empSalary FROM employee e1) a ON e.empSalary > a.empSalary
GROUP BY e.empDept;

答案 1 :(得分:1)

可能是子查询的内容,大致如下:

SELECT empID FROM TABLE t 
WHERE empSalary > (SELECT AVG(empSalary) FROM TABLE WHERE empDept = t.empDept)

但也可以使用可能表现更好的JOIN来完成:

SELECT empID FROM TABLE t
JOIN (SELECT empDept, AVG(empSalary) AS avgSalary FROM TABLE GROUP BY empDept) averages
ON t.empDept = averages.empDept
WHERE t.empSalary > averages.avgSalary

编辑:根据下面的第一条评论,更新后的问题需要稍微不同的内容。按部门计算,有多少员工高于整体平均工资:

SELECT empDept, count(empID) FROM
(SELECT empID, empDept from TABLE 
WHERE empSalary > (SELECT AVG(empSalary) FROM TABLE) aboveAverageEmployees
GROUP BY empDept