从最近的工资期起,仅返回25岁以上的员工

时间:2018-10-16 11:16:11

标签: sql sql-server sql-query-store

我有这个查询,我只希望最近RunID的雇员超过25岁。从我的结果中可以看出,它返回的是25岁以上的雇员和他们最近的RunID。我只希望最后一个RunID(2131)中的员工。下周,RunID将为(2132),并且每周都会增加。有没有办法只让雇员使用最后一个RunID?真的卡在这一个上。这是我的查询图片。<code>enter image description here</code>

SELECT DISTINCT
ed.EeID,
CONCAT(ed.Forename, '', ed.Surname) AS 'Name',
MAX(pr.RunID)
FROM EeDetails ed
INNER JOIN EeRunBals erb on erb.EeID = ed.EeID
INNER JOIN PayrollRuns pr on pr.RunID = erb.RunID
WHERE ed.BirthDate < '1994-01-01' 
--WHERE pr.RunID = MAX(pr.RunID)
GROUP BY ed.EeID, ed.Forename, ed.Surname, ed.BirthDate
ORDER BY ed.EeId

3 个答案:

答案 0 :(得分:2)

仅使用聚合怎么样?

SELECT ed.EeID, ed.Forename, ed.Surname, ed.BirthDate, MAX(pr.RunId)
FROM EeDetails ed INNER JOIN
     EeRunBals erb 
     ON erb.EeID = ed.EeID INNER JOIN
     PayrollRuns pr 
     ON pr.RunID = erb.RunID
WHERE ed.BirthDate < '1994-01-01' 
GROUP BY ed.EeID, ed.Forename, ed.Surname, ed.BirthDate
ORDER BY ed.EeId;

哦,我知道,您不希望每个人的最后一次跑步ID 。您想要总体上的最后一个。在这种情况下:

SELECT TOP (1) WITH TIES . . . 
FROM EeDetails ed INNER JOIN
     EeRunBals erb 
     ON erb.EeID = ed.EeID INNER JOIN
     PayrollRuns pr 
     ON pr.RunID = erb.RunID
WHERE ed.BirthDate < '1994-01-01' 
ORDER BY pr.RunId DESC;

这实际上获得了生日小于'1994-01-01'的某人的最后一次跑步ID。

答案 1 :(得分:1)

您可以使用:

DECLARE @MaxRunID = (select MAX(RunID) from PayrollRuns)

   SELECT DISTINCT
        ed.EeID,
        CONCAT(ed.Forename, '', ed.Surname) AS 'Name',
        MAX(pr.RunID)
    FROM EeDetails ed
        INNER JOIN EeRunBals erb on erb.EeID = ed.EeID
        INNER JOIN PayrollRuns pr on pr.RunID = erb.RunID
    WHERE   ed.BirthDate < '1994-01-01' 
        AND pr.RunID = @MaxRunID 
    GROUP BY ed.EeID, ed.Forename, ed.Surname, ed.BirthDate
    ORDER BY ed.EeId

或者,您可以绕过变量,而只是放置子查询,尽管变量更好。

答案 2 :(得分:1)

您可以使用hading子句来过滤汇总值,即max runid。另外,您还需要使用子查询来获取最大runid,因为在父查询中,MAX(pr.RunID)实际上是员工(分组依据)而不是所有员工的max runid。在您的代码中,您可以使用如下查询:

SELECT DISTINCT
ed.EeID,
CONCAT(ed.Forename, '', ed.Surname) AS 'Name',
MAX(pr.RunID)
FROM EeDetails ed
INNER JOIN EeRunBals erb on erb.EeID = ed.EeID
INNER JOIN PayrollRuns pr on pr.RunID = erb.RunID
WHERE ed.BirthDate < '1994-01-01'     
GROUP BY ed.EeID, ed.Forename, ed.Surname, ed.BirthDate
HAVING MAX(pr.RunID)=(select MAX(RunID) from PayrollRuns)
ORDER BY ed.EeId

希望这会有所帮助。