0

我有这个查询,我只想要最近的 RunID 上的员工以及他们超过 25 岁的位置。从我的结果中可以看出,它返回的是超过 25 岁的员工和他们最近的 RunID。我只想要最后一个 RunID(2131) 的员工。下周 RunID 将是 (2132) 并且每周都会上升。有没有办法只获取最后一个 RunID 上的员工?真的卡在这个了。这是我的查询中的图片。<code>在此输入图片说明</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
4

3 回答 3

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;

这实际上得到了生日小于的人的最后一次运行 id '1994-01-01'

于 2018-10-16T11:18:49.803 回答
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

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

于 2018-10-16T11:27:30.273 回答
1

您可以使用having 子句过滤聚合值,即max runid。此外,您需要使用子查询来获取最大 runid,因为在父查询中,MAX(pr.RunID)实际上是员工的最大 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

希望这可以帮助。

于 2018-10-16T11:36:24.210 回答