how select max(salary) of employee each department with employee_id and emp_name
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
Highest Salary in each department
SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID
The above query is the accepted answer but it will not work for the following scenario. Let's say we have to find the employees with the highest salary in each department for the below table.
DeptID | EmpName | Salary |
---|---|---|
Engg | Sam | 1000 |
Engg | Smith | 2000 |
Engg | Tom | 2000 |
HR | Denis | 1500 |
HR | Danny | 3000 |
IT | David | 2000 |
IT | John | 3000 |
Displaying last_name, Dept_id, (max)Salary
WITH RCounter AS (
SELECT department_id, last_Name, Salary,
DENSE_RANK() OVER(PARTITION BY department_id ORDER BY Salary DESC) AS RowNumberCounter
FROM <<tablename>>
)
SELECT department_id, last_Name, Salary
FROM RCounter
WHERE RowNumberCounter = 1;
Related Topics
Sql - Sum of Positive and Negative Numbers Using Subquery
Multiple Rows Output into Variables in MySQL
How Two Join to Tables Based on the Highest Value in One of Them
Error 1067 (42000): Invalid Default Value for 'Created_At'
Oracle Pl/Sql String Compare Issue
Formatting Numbers by Padding With Leading Zeros in SQL Server
Compare 2 Column Values in Same Table
Is There a Command to Test an SQL Query Without Executing It ( MySQL or Ansi SQL )
Postgresql Error: Fatal: Role "Username" Does Not Exist
Update Multiple Rows in a Table from Another Table When Condition Exists
Two Rows With the Same Id and Two Different Values, Getting the Second Value into Another Column
Sql String: Counting Words Inside a String
Combining Multiple Rows in SQL Server into One
How to Get Last 7 Days Data from Current Datetime to Last 7 Days in SQL Server
How to Use Json_Extract in MySQL and Get a String Without the Quotes
Select All Rows With the Same Value in Column 1 But Different Values in Columns 2 and 3 Using SQL
Sql Server Query to Find All Permissions/Access for All Users in a Database