簡體   English   中英

使用SQL Find, Most Current Salary of each employee(注意-一個員工在不同日期有很多工資記錄)

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

在我的工資表中,每個員工在不同的持續時間內都有多個工資(一對多關系)。 這些不同的持續時間在薪水表中記錄為“from_date”和“to_date”列。 這是薪水表的片段:

Select * FROM salaries

工資表的片段

我怎樣才能得到一個 output 向我顯示一個表,其中包含員工編號、from_date(基於最新的薪水日期)和最新的薪水。 所以基本上我試圖回答 -每個員工的最新工資是多少?

我嘗試過,但我只能獲得每個員工的員工編號和最大 from_date,但我無法提取最新的薪水,我沒有在此處的 SELECT 語句中輸入薪水,因為這將顯示一名員工的所有薪水, 而且, 不是最新的薪水。 這是我得到的代碼和 output:

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

以上代碼的Output

我追求的最終結果是:在我的 output 中,我希望第三列作為每個 employee_no 的工資列,基於他們最新的工資 Max(from_date)。 考慮到我在 output 匯總工資欄中的內容是不需要的。

您沒有在查詢中選擇薪水。

請嘗試:

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

如果您想根據emp_no總薪水,請嘗試:

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

以下是給出答案的兩種方法:

第一種方法 - 通過創建薪水表的兩個實例(t1 和 t2)來運行子查詢:

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 通過第一種方法

第二種方法 - 使用 window function 方法,如 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 通過第二種方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM