如何根据同一个表中另一个字段的Max获取字段ID

时间:2010-12-17 19:51:56

标签: sql ms-access

我有一个名为ae_types的表。它包含三个与我的问题相关的字段:

aetId               This is Auto Increment and is the Primary Key
aetProposalType     Text field 5 characters long
aetDaysToWait       Byte data type

aetProposalTypeaetDaysToWait位于一个唯一键中,因此我保证永远不会有两个aetProposalType具有相同的aetDaysToWait

我要查找的结果是获取每个aetId最大aetDaysToWait字段的aetProposalType

以下是我为实现这一目标而提出的查询,但在我看来,这可能是不必要的复杂而且不是很漂亮。

SELECT ae_types.aetId AS lastEmailId, ae_types.aetProposalType
FROM ae_types INNER JOIN 

(SELECT ae_types.aetProposalType, Max(ae_types.aetDaysToWait) AS MaxOfaetDaysToWait 
FROM ae_types GROUP BY ae_types.aetProposalType)  AS ae_maxDaysToWaitByProposalType 

ON (ae_types.aetDaysToWait = ae_maxDaysToWaitByProposalType.MaxOfaetDaysToWait) 
AND (ae_types.aetProposalType = ae_maxDaysToWaitByProposalType.aetProposalType);

有哪些替代解决方案,为什么它们会更好?

PS如果您有任何疑问,请询问,我将很乐意尝试提供答案。

1 个答案:

答案 0 :(得分:1)

这也是我这样做的方式。

select a.aetId, a.aetProposalType, a.aetDaysToWait
    from ae_types a
        inner join (select aetProposalType, max(aetDaysToWait) as MaxDays
                    from ae_types
                    group by aetProposalType) sq
            on a.aetProposalType = sq.aetProposalType
                and a.aetDaysToWait = sq.MaxDays