SQL COUNT修改

时间:2018-02-21 14:41:22

标签: sql oracle count

从SQL Oracle HR方案中我使用了以下内容:

SELECT DEPARTMENT_ID, ROUND(AVG(SALARY),2) 
FROM EMPLOYEES 
WHERE DEPARTMENT_ID IS NOT NULL 
GROUP BY DEPARTMENT_ID 
ORDER BY DEPARTMENT_ID

获得:

DEPARTMENT_ID   ROUND(AVG(SALARY),2)
10                   4400
20                   9500   
30                   4150
40                   6500
50                   3475,56
60                   5760

...

如何更改它:它只计算具有最高平均工资的部门(在我的情况下为1)并显示最高平均工资? 谢谢你的时间!

2 个答案:

答案 0 :(得分:0)

如果我理解你,这是一种可能的方式:

SELECT DEPARTMENT_ID, ROUND(AVG(SALARY),2) AS AVG_SALARY
FROM EMPLOYEES
WHERE DEPARTMENT_ID IS NOT NULL
AND   ROUND(AVG(SALARY),2) = (
    SELECT MAX(T.AVG_SALARY)
    FROM (
        SELECT DEPARTMENT_ID, ROUND(AVG(SALARY),2) AS AVG_SALARY
        FROM EMPLOYEES 
        WHERE DEPARTMENT_ID IS NOT NULL
        GROUP BY DEPARTMENT_ID) AS T)
GROUP BY DEPARTMENT_ID
ORDER BY DEPARTMENT_ID

这将显示所有具有最高平均薪水的部门。如果您只想要计数:

SELECT COUNT(A.*), AVG(A.AVG_SALARY)
FROM (
    SELECT DEPARTMENT_ID, ROUND(AVG(SALARY),2) AS AVG_SALARY
    FROM EMPLOYEES 
    WHERE DEPARTMENT_ID IS NOT NULL
    GROUP BY DEPARTMENT_ID) A
WHERE A.AVG_SALARY = (
        SELECT MAX(T.AVG_SALARY) AS MAX_AVG_SALARY
        FROM (
            SELECT DEPARTMENT_ID, ROUND(AVG(SALARY),2) AS AVG_SALARY
            FROM EMPLOYEES 
            WHERE DEPARTMENT_ID IS NOT NULL
            GROUP BY DEPARTMENT_ID) AS T)

答案 1 :(得分:0)

使用连接的另一种方法:

SELECT t1.DEPARTMENT_ID, ROUND(AVG(t1.SALARY),2) AS AVG_SALARY
FROM EMPLOYEES t1
LEFT JOIN (SELECT MAX(AVG_SALARY) AS MAX_AVG_SALARY FROM EMPLOYEES) t2
  ON AVG_SALARY=t2.MAX_AVG_SALARY
  WHERE t1.DEPARTMENT_ID IS NOT NULL 
   AND AVG_SALARY=t2.MAX_AVG_SALARY
ORDER BY t1.DEPARTMENT_ID ASC;

我使用oracle在我的样本表上测试了这个想法,并使用以下代码在w3schools sql testing page上测试:

SELECT Customers.CustomerName, Orders.maxid
FROM Customers
LEFT JOIN (select max(Orders.CustomerID) as maxid from Orders) orders
ON Customers.CustomerID=Orders.maxid
where customers.customername is not null and customers.customerid=orders.maxid
ORDER BY orders.maxid desc;

它应该只抓住与平均工资相匹配的部门和在连接声明中选择的最高平均工资。

如果您只是在寻找部门的数量,而不是部门名称的列表,那么这个稍微修改应该适合您:

SELECT COUNT(t1.DEPARTMENT_ID) as Num_Of_Depts, ROUND(AVG(t1.SALARY),2) AS AVG_SALARY
FROM EMPLOYEES t1
LEFT JOIN (SELECT MAX(AVG_SALARY) AS MAX_AVG_SALARY FROM EMPLOYEES) t2
  ON AVG_SALARY=t2.MAX_AVG_SALARY
  WHERE t1.DEPARTMENT_ID IS NOT NULL 
   AND AVG_SALARY=t2.MAX_AVG_SALARY
GROUP BY AVG_SALARY;