I have an emp_salary table with emp_id, salary and salary_date. I want to write a query to find out which employee was paid highest in every month

StackOverflow https://stackoverflow.com/questions/23395579

Question

Following is the table:

emp_id    salary   salary_date
Emp1    1000    Feb 01
Emp1    2000    Feb 15
Emp1    3000    Feb 28
Emp1    4000    Mar 01
Emp2    5000    Jan 01
Emp2    6000    Jan 15
Emp2    2000    Mar 01
Emp2    5000    Apr 01
Emp3    1000    Jan 01
Emp4    3000    Dec 31
Emp4    5000    Dec 01

And I want the following result:

Emp1  Feb           3000 
Emp2  Jan           6000 
Emp4  Dec           5000 
Emp2  Apr           5000 
Emp1  Mar           4000 
Was it helpful?

Solution 3

I have found my answer!!!

select emp_id, substr(sal_date,1,3) monthly, salary from (select emp_id, sal_date, salary, max(salary)over (partition by substr(sal_date,1,3)) max_sal from emp_salary order by emp_id) where salary=max_sal;

Result-set:

EMP_ID MONTHLY SALARY


Emp1 Mar 4000 Emp1 Feb 3000 Emp2 Jan 6000 Emp2 Apr 5000 Emp4 Dec 5000

OTHER TIPS

SELECT e.Emp_ID,MaxSalary,MonthName
FROM employeeTable e
INNER JOIN
(
SELECT MAX(salary) as MaxSalary,
       LEFT(salary_date,3) as MonthName
FROM employeeTable
GROUP BY LEFT(salary_date,3)
)t
ON e.Salary=t.MaxSalary

Here's my take on it using the nice RANK() function:

SELECT emp_id, to_char(salary_date, 'MM, YYYY'), salary FROM (
  SELECT emp_id, salary_date, salary,
  rank() over (partition BY to_char(salary_date, 'MM-YYYY') ORDER BY salary DESC) rnk
  FROM emp_salary) WHERE rnk = 1

Output:

EMP_ID  MONTHYEAR   SALARY
Emp2    01, 2014    6000
Emp1    02, 2014    3000
Emp1    03, 2014    4000
Emp2    04, 2014    5000
Emp4    12, 2014    5000

Here's the SQL Fiddle to play with the data and query: http://sqlfiddle.com/#!4/e58eaa/32

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top