首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在having子句中使用别名使用子查询

问在having子句中使用别名使用子查询
EN

Stack Overflow用户
提问于 2016-09-02 05:12:41
回答 3查看 1K关注 0票数 0

我有一个Mysql查询,其中

其中我有一个如下所示的表(示例数据)

代码语言:javascript
复制
Employee_id Months Salary
  1         10      200
  2         20      300
  3         30      400

现在我想找出具有最大总工资的员工数量(总工资=月*工资)

所以我的查询是这样的

子查询:

代码语言:javascript
复制
((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)

//求总工资的最大值

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

代码语言:javascript
复制
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)

它显示错误。我在使用max_mon_sal alias.Please建议时遇到问题。

EN

回答 3

Stack Overflow用户

发布于 2016-09-02 05:57:27

您可以简单地使用:

代码语言:javascript
复制
select count(*)
from employee
where months * salary = (
  select max(months * salary)
  from employee
);
票数 5
EN

Stack Overflow用户

发布于 2016-09-02 05:58:11

代码语言:javascript
复制
SELECT COUNT(*) no_of_employees
  FROM my_table a 
  JOIN 
     ( SELECT MAX(months*salary) total FROM my_table ) b 
    ON b.total = a.months * a.salary;
票数 1
EN

Stack Overflow用户

发布于 2016-09-02 05:35:15

我不确定这是否是我们想要的,即使是这种情况下更好的解决方案也是使用临时表:

代码语言:javascript
复制
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
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39280932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档