在使用别名的子句中使用子查询

时间:2016-09-01 21:12:41

标签: mysql sql

我有一个Mysql查询

我的桌子如下(样本数据)

Employee_id Months Salary
  1         10      200
  2         20      300
  3         30      400

现在我想找到拥有最高总薪水的员工人数 (总薪水=月*工资)

所以我有这样的查询

子查询:

((select max(mon_sal.mc) as max_mc from (
  select months*salary as mc from employee group by employee_id) as mon_sal)
as max_mon_sal)

//查找总薪资最高

现在我的问题是我需要找到最高工资的人数,

select max_mon_sal.max_mc,name 
from employee group by employee_id 
having salary=max_mon_sal.max_mc from (
    (select max(mon_sal.mc) as max_mc from 
      (select months*salary as mc from employee group by employee_id) as mon_sal)
    as max_mon_sal)

显示Error.I有使用max_mon_sal别名的问题。请建议。

3 个答案:

答案 0 :(得分:5)

您可以简单地使用:

select count(*)
from employee
where months * salary = (
  select max(months * salary)
  from employee
);

答案 1 :(得分:1)

{{1}}

答案 2 :(得分:-1)

我不确定这是否正在寻找,即使是这种情况的更好的解决方案是使用临时表:

SELECT Employee.employee_id,SUM(MONTHs * salary) 
FROM Employee,
   ( 
      SELECT MAX(total) value FROM (
           SELECT SUM(MONTHs * salary) as total
           FROM Employee
           GROUP BY employee_id
      ) T
   ) D
   GROUP BY Employee.employee_id,D.value
   HAVING SUM(MONTHs * salary)  = D.value