聚合函数中的多行

时间:2013-06-26 20:15:04

标签: sql ms-access

我一天中大部分时间都在浏览这个网站和其他许多网站,并且还没有为我的问题找到解决方案。

我目前正在尝试在MS Access上运行一个查询,该查询将提取以下列:

问题是我需要里程碑成为最近的里程碑。 due_date对应于此里程碑。

使用自动编号ID输入每个里程碑,我一直在尝试使用此ID将我的查询整合在一起。

此查询:

SELECT E.EID, E.[CN], E.[AN], E.Status, MAX(M.ID) AS Milestone_ID
FROM [Pilot Milestone] AS M, [PP Engagements] AS E, [Pilot Milestone] AS D
WHERE E.EID=M.EID
GROUP BY M.EID, E.EID, E.[CN], E.[AN], E.Status, E.[Estimated Hours]

为每个EID留下最新的里程碑ID。但是,如果我添加Due_Dates:

SELECT E.EID, E.[CN], E.[AN], E.Status, MAX(M.ID) AS Milestone_ID, M.(Due Date)
FROM [Pilot Milestone] AS M, [PP Engagements] AS E, [Pilot Milestone] AS D
WHERE E.EID=M.EID
GROUP BY M.EID, E.EID, E.[CN], E.[AN], E.Status, E.[Estimated Hours], M.(Due Date)

我收到了两张额外的EID 30记录。这些是唯一两条记录的截止日期,而 则不反映最新的里程碑ID。

此外,每个EID都有多个里程碑,因此如果我在查询中输入里程碑描述的方式与截止日期相同,我会遇到类似的问题。

非常感谢任何帮助。

由于

REVISED

以下查询为我的due_dates提供了结果,没有任何重复,因为我刚刚在MS Access 2007中测试过。但是,无论是否来自最近的里程碑,查询都会提取最新日期。

SELECT E.EID, E.[Client Name], E.[Audit Name], E.Status, MAX(M.ID) AS Milestone_ID, (
SELECT MAX ([Due Date]) FROM [Pilot Milestone] AS M2 WHERE M2.EID = M.EID) AS Due_Date
FROM [Pilot Milestone] AS M, [Potential Pilot Engagements] AS E
WHERE E.EID=M.EID
GROUP BY M.EID, E.EID, E.[Client Name], E.[Audit Name], E.Status, E.[Estimated Hours]

另外,我不确定如何将Milestone描述添加到结果中,而不将其作为聚合函数的一部分添加(导致重复)或将其添加到导致多个记录和错误的子查询中

SELECT E.EID, E.[Client Name], E.[Audit Name], E.Status, MAX(M.ID) AS Milestone_ID, (
SELECT MAX ([Due Date]) FROM [Pilot Milestone] AS M2 WHERE M2.EID = M.EID) AS Due_Date, (
SELECT (Milestone) FROM [Pilot Milestone] AS M3 WHERE M3.EID = M.EID) AS Milestone
FROM [Pilot Milestone] AS M, [Potential Pilot Engagements] AS E
WHERE E.EID=M.EID
GROUP BY M.EID, E.EID, E.[Client Name], E.[Audit Name], E.Status, E.[Estimated Hours]

1 个答案:

答案 0 :(得分:0)

此查询将为您提供最新Milestone_ID列表以及每个Milestone_ID的最新截止日期

SELECT 
    E.[EID], E.[CN], E.[AN], M.[Milestone], E.[Status], MAX(M.[ID]) AS Milestone_ID, (
        SELECT MAX([Due Date]) FROM [Pilot Milestone] AS M2 WHERE M2.[ID]=MAX(M.[ID]) AND M2.[EID]=M.[EID]
        ) as Due_Date
FROM 
    [Pilot Milestone] AS M
    INNER JOIN [PP Engagements] AS E ON E.[EID]=M.[EID]
GROUP BY E.[EID], E.[CN], E.[AN], M.[Milestone], E.[Status]