mysql SQL查询,找出每月获得最高工资的员工的姓名和工资

j8yoct9x  于 2023-06-04  发布在  Mysql
关注(0)|答案(1)|浏览(233)

SQL在这里你可以看到我写下面的代码,给出了id和薪水的输出,但我想要的名字和薪水

CREATE TABLE salary_data (
      id INTEGER NOT NULL,
      month INTEGER NOT NULL,
      salary INTEGER NOT NULL
    );
    -- another TABLE
    CREATE TABLE emp_data (
        id INTEGER NOT NULL,
        name TEXT NOT NULL);
    -- insert some values
    INSERT INTO salary_data VALUES (1, 3,50000);
    INSERT INTO salary_data VALUES (2,4,45000);
    INSERT INTO salary_data VALUES (3,3,36000);
    INSERT INTO salary_data VALUES (4,5,72000);
    INSERT INTO salary_data VALUES (1,6,49000);
    INSERT INTO salary_data VALUES (4,4,51000);
    INSERT INTO salary_data VALUES (2,5,64000);
    INSERT INTO emp_data VALUES (1, "RAMESH");
    INSERT INTO emp_data VALUES (2, "SURESH");
    INSERT INTO emp_data VALUES (3, "NIKHIL");
    INSERT INTO emp_data VALUES (4, "RAJEEV");
    -- fetch some values
    SELECT id,max(salary) FROM salary_data GROUP BY month;

我想我在最后一行漏掉了一些
我想要这种类型的输出
姓名工资,
拉梅什50000
就像那样

ozxc1zmp

ozxc1zmp1#

你做了第一步,错过了第二步。你找到了每月最高的工资。现在发现员工赚那么多。
这里有一种方法可以做到这一点:

select *
from salary_data s
join emp_data e on e.id = s.id -- s.id is a misnomer for s.emp_id
where (s.month, s.salary) in
(
  select month, max(salary)
  from salary_data
  group by month
);

下面是另一个(仅在MySQL 8之后才可能):

select *
from
(
  select
    id as emp_id, month, salary, 
    max(salary) over (partition by month) as max_salary_for_the_month
  from salary_data
) s
join emp_data e on e.id = s.emp_id
where s.salary = s.max_salary_for_the_month
order by s.month;

相关问题