如何使用employee_id和emp_name选择每个部门的员工最高薪水

时间:2018-12-26 13:48:05

标签: sql oracle-sqldeveloper

我想选择每个部门的emp_id,department_id,max(salary),但我按部门编号使用group_id,并且出现错误ora-00979

3列在同一表(员工)

我该如何解决

select  department_id, employee_id as "ID",first_name || ' ' || last_name as "Name",max(salary)as "SALARY"
from EMPLOYEES
group by  department_id
order by department_id;

5 个答案:

答案 0 :(得分:2)

您可以使用keep

select  department_id,
        max(employee_id) keep (dense_rank first order by salary desc) as "ID",
        max(first_name || ' ' || last_name) keep (dense_rank first order by salary desc, employee_id desc) as "Name", 
        max(salary) as "SALARY"
from employees e
group by  department_id
order by department_id;

答案 1 :(得分:0)

使用具有department_id和最高薪水的子查询,然后加入主表:

private async void getCustBalance()
        {
            HttpClient client = new HttpClient();

            string x = FormEntryBindings.AppLoginUserName;

            int custid =  GetCustomerId(x);

请参见demo


员工

select 
  e.department_id, 
  t.employee_id as id,
  t.first_name || ' ' || t.last_name as name,
  e.maxsalary 
from (
  select 
    department_id, 
    max(salary) as maxsalary 
  from 
    EMPLOYEES
  group by 
    department_id 
) e
inner join 
  EMPLOYEES t 
on 
  t.department_id = e.department_id and t.salary = e.maxsalary
order by e.department_id;

结果

EMPLOYEE_ID DEPARTMENT_ID   SALARY  FIRST_NAME  LAST_NAME
    1          1            10000       A           B
    2          1            20000       C           D
    3          1            150000      E           F
    4          2            12000       G           H
    5          2            10000       I           J
    6          3            20000       K           L
    7          4            11000       M           N
    8          4            11000       O           P
    9          4            11000       Q           R
    10         4            10000       S           T

答案 2 :(得分:0)

错误是因为employee_id不在组中。

可能的解决方案是:

select department_id, ID, Name, SALARY
from (
    select distinct department_id, 
        first_value(employee_id) over (partition by department_id order by salary desc) as ID,
        first_value(first_name || ' ' || last_name) over (partition by department_id order by salary desc) as Name,
        first_value(salary) over (partition by department_id order by salary desc)as SALARY
    from EMPLOYEES
)
order by department_id;

答案 3 :(得分:0)

尝试一下:

SELECT department_id, salary AS "Salary", employee_id AS "ID", first_name || ' ' || last_name AS "Name" FROM employees 
WHERE salary = (SELECT MAX(salary) FROM employees) GROUP BY department_id;

我希望它能起作用。 :)

答案 4 :(得分:-1)

使用以下查询:

SELECT e.department_id,e.employee_id,
  e.first_name||' '|| e.last_name AS emp_name,t1.max_sal
FROM
  (SELECT department_id,
    MAX(salary) AS max_sal
  FROM employees
  GROUP BY department_id
  ) t1
JOIN employees e
ON t1.department_id = e.department_id
AND t1.max_sal = e.salary
order by e.department_id;