从一列到第二列中选择最大值

时间:2015-02-13 10:48:39

标签: mysql sql

我有两张桌子:

EMPLOYEES
=====================================================
ID    NAME    SUPERVISOR    LOCATION    SALARY
-----------------------------------------------------
34       John                  AL          100000
17       Mike    34            NY          75000
5        Alan    34            LE          25000
10       Dave    5             NY          20000

BONUS
========================================
ID        Bonus
----------------------------------------
17        5000
34        5000
10        2000

我必须编写查询,其中返回每个位置中收入最高的员工的名单,包括他们的姓名,工资和工资+奖金。排名应基于工资加奖金。所以我写了这个查询:

select em.name as name, em.salary as salary, bo.bonus as bonus, max(em.salary+bo.bonus) as total
from employees as em
join bonus as bo on em.empid = bo.empid 
group by em.location

但是我得到错误的名字和查询不会返回没有奖金的员工(员工表中的empid = 5),这些员工的薪水最高(25000 + 0奖金)。

4 个答案:

答案 0 :(得分:1)

也许尝试使用left join

select em.name as name, em.salary as salary, bo.bonus as bonus, max(em.salary+bo.bonus) as total
from employees as em
left join bonus as bo on em.empid = bo.empid 
group by em.location

答案 1 :(得分:1)

你可以做

select 
  em.location, 
  em.name as name, 
  em.salary as salary, 
  IFNULL(bo.bonus,0)) as bonus, 
  max(em.salary+IFNULL(bo.bonus,0)) as total
from employees as em
left join bonus as bo on em.empid = bo.empid 
group by em.location;

但是,此查询依赖于特定于MySQL的行为,并且在大多数其他数据库中也会失败(如果启用了设置ONLY_FULL_GROUP_BY,也会在MySQL的更高版本中失败)。

我建议使用下面的查询:

select 
  em.location, 
  em.name as name, 
  em.salary as salary, 
  IFNULL(bo.bonus,0)) as bonus, 
  highest.total
from employees as em 
left join bonus as bo on em.empid = bo.empid 
join (
    select 
      em.location, 
      max(em.salary+IFNULL(bo.bonus,0)) as total
    from employees as em 
    left join bonus as bo on em.empid = bo.empid 
    group by em.location
) highest on em.LOCATION = highest.LOCATION and em.salary+IFNULL(bo.bonus,0) = highest.total;

在此确定每个位置的最高工资+奖金,并将该结果用作联接中的派生表,以过滤掉每个位置总数最高的员工。

请参阅此SQL Fiddle

答案 2 :(得分:0)

应该是:

select 
   em.name as name, 
   em.salary as salary, 
   COALESCE(bo.bonus,0) as bonus, 
   max(em.salary + COALESCE(bo.bonus,0) ) as total
from employees as em
left join bonus as bo on em.empid = bo.empid 
group by em.location

您可以在SQLFiddle

中查看

答案 3 :(得分:0)

请试试这个:

 select em.name as name, em.salary as salary,ISNULL(bo.bonus,0) as bonus,
     max(em.salary+ISNULL(bo.bonus,0)) as total
    from employees as em
    left join bonus as bo on em.ID = bo.ID 
    group by  em.name,em.salary, bo.bonus order by MAX(em.salary+ISNULL(bo.bonus,0)) Desc