gpt4 book ai didi

MySQL - SELECT MAX(), 并获取相应字段

转载 作者:行者123 更新时间:2023-11-29 02:48:06 24 4
gpt4 key购买 nike

任务是:获取每个员工的ID和他上一个工作部门的ID的列表。它变得越来越复杂,因为一个人可以同时在不同的部门工作,所以我们需要得到他最后一个拥有最大比率的部门。

表格:

 ID_employee| ID_department | end_date  |   rate
1 22 2016-01-01 1
2 25 NULL 0.3
2 27 NULL 1
3 22 2013-12-12 0.5
3 22 2014-05-05 0.5

end_date是员工工作的最后一天,NULL值表示他的契约(Contract)在今天生效。

结果必须如下所示:

ID_employee | ID_department | end_date  |   rate
1 22 2016-01-01 1
2 27 NULL 1
3 22 2014-05-05 0.5

我发现了如何使用 join 来选择具有相应字段的 max():

SELECT table.id_employee, id_department
FROM table
JOIN ( SELECT id_employee,
IF (MAX( end_date IS NULL ) = 1 , "0000-00-00", MAX( end_date )) as max_end_date
FROM table GROUP BY id_employee) maxs ON maxs.id_employee = table.id_employee
WHERE maxs.max_end_date = IFNULL(table.end_date, "0000-00-00")
GROUP BY table.id_employee

但是,结果中有所有对应的行:

ID_employee | ID_department | end_date  |   rate
1 22 2016-01-01 1
2 25 NULL 0.3
2 27 NULL 1
3 22 2014-05-05 0.5

问题是,如何不仅获得与 MAX(end_date) 对应的行,还获得与 MAX(rate) 对应的行?我认为 HAVING 可能会有所帮助,但我仍然不知道那里到底有什么。

也许还有其他方法可以更好地解决问题,因为这个查询大约需要 16 秒,而表有大约 30 000 行。

最佳答案

你能试试下面的查询吗:

SELECT  T1.ID_employee,  
T1.ID_department,
CASE WHEN maxs.max_end_date = "0000-00-00" THEN NULL ELSE maxs.max_end_date END AS end_date,
T1.rate
FROM TestTable T1
JOIN ( SELECT id_employee,
MAX(ID_department) AS ID_department,
IF (MAX( end_date IS NULL ) = 1, "0000-00-00", MAX( end_date )) AS max_end_date
FROM TestTable
GROUP BY id_employee ) maxs ON maxs.id_employee = T1.id_employee AND maxs.ID_department = T1.ID_department
WHERE maxs.max_end_date = IFNULL(T1.end_date, "0000-00-00")
GROUP BY T1.id_employee

请找到 Live Demo

更新:

根据评论,以下查询有助于实现结果:

SET @CurrentDate := CURDATE();

SELECT T2.ID_employee,
T2.ID_department,
CASE WHEN MR.Max_end_date = @CurrentDate THEN NULL ELSE T2.end_date END AS end_date,
MR.MaxRate AS rate
FROM TestTable T2
JOIN (
SELECT T1.ID_employee, MAX(T1.rate) AS MaxRate, MD.Max_end_date
FROM TestTable T1
JOIN (
SELECT ID_employee,
MAX(CASE WHEN end_date IS NULL THEN @CurrentDate ELSE end_date END) AS Max_end_date
FROM TestTable
GROUP BY ID_employee
) MD ON MD.ID_employee = T1.ID_employee
WHERE MD.Max_end_date = IFNULL(T1.end_date, @CurrentDate)
GROUP BY T1.ID_employee
) MR ON MR.ID_employee = T2.ID_employee AND MR.MaxRate = T2.rate
WHERE MR.Max_end_date = IFNULL(T2.end_date, @CurrentDate)

Working Demo

关于MySQL - SELECT MAX(), 并获取相应字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39411833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com