简体   繁体   中英

Using SQL Find, Most Current Salary of each employee (note - One employee has many salary records on different dates)

In my salaries table each employee has multiple salaries (one to many relationship) in various durations. These various durations are recorded within salaries table as columns "from_date" and "to_date". Here's a snippet of salaries table:

Select * FROM salaries

Snippet of Salaries table

How can I get an output that shows me a table that has employee number, from_date (based on most current salary date) and the most current salary. So basically I'm trying to answer - What is the most current salary of each employee?

I attempted and I could only get the employee number and the maximum from_date for each employee, but I am not able to pull most current salary, I have not put salary in the SELECT statement here because that will show me all the salaries of an employee, and, not the most current salary. Here's the code and the output I got:

SELECT emp_no, Max(from_date) as "Most Current Salary Date"
from salaries
group by emp_no

Output of above code

End result I'm after is: In my output I want third column as salary column for each employee_no on the basis of their most current salary Max(from_date). Considering what I'm after in the output aggregating on salary column is not required.

You are not selecting salary in query.

Please try:

SELECT emp_no, salary, Max(from_date) as "Most Current Salary Date"
from salaries
group by emp_no

If you want to sum total salary based on emp_no then please try:

SELECT emp_no, SUM(salary) as total_salary, Max(from_date) as "Most Current Salary Date"
    from salaries
    group by emp_no

Below are the two approaches that gave the answer:

First approach - Running Sub-Query by creating two instance (t1 and t2) of salaries table:

WITH temp as
(
SELECT emp_no as `Employee ID`, max(from_date) as `Most Recent Salary Date`
FROM salaries
group by emp_no
)
SELECT t1.`Employee ID`, t1.`Most Recent Salary Date`, t2.salary as `Most Current Salary`
FROM temp t1 LEFT JOIN salaries t2 ON (t1.`Employee ID` = t2.emp_no)
WHERE t1.`Most Recent Salary Date` = t2.from_date

Output via first approach

Second approach - Using window function methods like Row Number(), Partition By():

WITH temp as
(SELECT emp_no as `Employee ID`, from_date as `Most Recent Salary Date`, salary as `Most Current Salary`, row_number() OVER (partition by emp_no order by from_date desc) as 'Row Number'
FROM salaries
)
SELECT `Employee ID`, `Most Recent Salary Date`, `Most Current Salary` 
FROM temp
WHERE `Row Number` = 1

Output via second approach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM