问题
I want to select emp_id,department_id,max(salary) each department but I use group by department_id and it has error ora-00979
3 column is in the same table(employees)
How can I fix it
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;
回答1:
You can use 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;
回答2:
Try this one:
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;
I hope it works. :)
回答3:
The error is because employee_id is not in the group.
A possible solution is:
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;
回答4:
Use a subquery with department_id and the max salary and then join to the main table:
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;
See the demo
EMPLOYEES
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
Result
DEPARTMENT_ID ID NAME MAXSALARY
1 3 E F 150000
2 4 G H 12000
3 6 K L 20000
4 7 M N 11000
4 8 O P 11000
4 9 Q R 11000
回答5:
use below query :
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;
来源:https://stackoverflow.com/questions/53932956/how-select-maxsalary-of-employee-each-department-with-employee-id-and-emp-name