I have a table named ae_types
. It contains three fields that are relevant to my question:
aetId This is Auto Increment and is the Primary Key
aetProposalType Text field 5 characters long
aetDaysToWait Byte data type
aetProposalType
and aetDaysToWait
are in a unique key so that I am guaranteed that there will never be two aetProposalType
s with the same aetDaysToWait
.
The result that I am looking for is to get the aetId
of the field with the largest aetDaysToWait
for each aetProposalType
.
Below is the query that I have come up with to accomplish this, but it seems to me like it is possibly unnecessarily complicated and not very beautiful.
SELECT a开发者_运维知识库e_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);
What are some alternative solutions and why would they be better?
PS If you have any questions please ask and I will be happy to attempt to provide the answer.
That's the way I'd do it too.
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
精彩评论