根据MAX值和GROUP BY选择完整行

时间:2017-11-17 22:46:56

标签: php mysql select group-by max

这是场景。我有员工,他们每年评估不同的类别。我需要:每个类别的最新评估的完整行。

示例:

员工表:

EmpID  Name
454    John

Evals Table:

id EmpID  Category  EvalDate     Note
1  454       A      2016-01-01   Excellent
2  454       A      2017-02-15   Not so good
3  454       B      2016-01-01   Poor
4  454       B      2017-02-01   Good

我需要一个返回每个类别的最新eval(完整行)的查询:

EmpID  Category  EvalDate     Note
454       A      2017-02-15   Not so good
454       B      2017-02-01   Good

到目前为止我的查询:

SELECT 
    evals.EmpID,
    evals.Category,
    evals.Note,
    MAX(evals.EvalDate) as LatestEval
FROM
    evals
WHERE 
    evals.EmpID = 454
GROUP BY
    evals.Category

不幸的是,这会返回每个类别的最新日期,但会从较旧的evals中返回注释字段。

1 个答案:

答案 0 :(得分:2)

你可以尝试一下:

SELECT
    evals.EmpID,
    evals.Category,
    evals.Note,
    evals.EvalDate
FROM Employee emp
JOIN Evals evals
ON emp.EmpID = evals.EmpID
AND eval.EvalDate = 
    (SELECT MAX(EvalDate) 
    FROM Evals a 
    WHERE a.Category = evals.category 
        AND a.EmpID = emp.EmpID GROUP BY e.EmpID,e.Category)
GROUP BY evals.EmpID,evals.Category