SUM结果的子查询AVG

时间:2015-04-20 10:20:28

标签: mysql sql subquery isql

我遇到了子查询的问题。     所以我想列出那些工作总时数大于全体员工平均工作时间的员工。     但是使用此代码,它会将另一名员工每小时工作的小时数与另一名员工的小时数进行比较。     所以这是总结:     员工总工作时数>所有员工工作总时数的平均值 - >何时hrs_worked> AVG(SUM(HRS_WORKED))这就是我想要的。

SELECT employee.emp_id,
       employee.emp_name,
       SUM(action.hrs_worked) AS "Total Hours Worked"
FROM action
INNER JOIN allocation ON action.act_id = allocation.act_id
AND action.emp_id = allocation.emp_id
INNER JOIN employee ON allocation.emp_id = employee.emp_id
WHERE action.hrs_worked >
    (SELECT AVG(action.hrs_worked)
     FROM action)
GROUP BY employee.emp_id,
         employee.emp_name
ORDER BY SUM(action.hrs_worked) DESC

2 个答案:

答案 0 :(得分:0)

应该是这样的:

SELECT * 
FROM  Orders
........... 
WHERE Price > (
           SELECT AVG(sum_pr) 
           FROM (
              SELECT SUM(Price) as sum_pr 
              FROM Orders 
              GROUP BY Price
                 )x
               )

答案 1 :(得分:0)

让我们留下员工的姓名。总工作时间是:

SELECT a.emp_id, SUM(a.hrs_worked) AS TotalHoursWorked
FROM action a 
GROUP by a.emp_id;

要获得大于avg的值:

SELECT a.emp_id, SUM(a.hrs_worked) AS TotalHoursWorked
FROM action a 
GROUP by a.emp_id;
HAVING TotalHoursWorked > (SELECT avg(TotalHoursWorked)
                           FROM (SELECT a.emp_id, SUM(a.hrs_worked) AS TotalHoursWorked
                                 FROM action a 
                                 GROUP by a.emp_id
                                ) a2
                           );

您可以使用join引入您想要的其他字段。

根据您的查询,我不知道如何使用allocation