MS Access Query基于单个列获取唯一行

时间:2015-04-16 22:39:30

标签: sql ms-access

我的查询为:

SELECT MAX(SubmissionLog.ID), AccountTypes.Description, 
AccountContacts.FirstName, AccountContacts.LastName,  Accounts.Name, 
Accounts.StreetAddress, Accounts.MailAddress,SubmissionLog.EffectiveDate, 
SubmissionLog.ExpirationDate, StatusCodes.Description
FROM 
AccountContacts RIGHT JOIN (StatusReasons 
RIGHT JOIN ([JILL_MG utah sub query] 
RIGHT JOIN (StatusCodes 
RIGHT JOIN (Carriers 
RIGHT JOIN (AgencyLocations 
RIGHT JOIN (Brokers 
RIGHT JOIN (Agencies 
RIGHT JOIN (SubmissionLog 
LEFT JOIN (AccountTypes 
RIGHT JOIN (BusinessTypes 
RIGHT JOIN Accounts ON BusinessTypes.ID = Accounts.BusinessTypeID) 
ON AccountTypes.ID = Accounts.AccountTypeID) 
ON SubmissionLog.AccountID = Accounts.ID) 
ON Agencies.ID = SubmissionLog.AgencyID) 
ON Brokers.ID = SubmissionLog.BrokerID) 
ON (AgencyLocations.LocationID = Brokers.AgencyLocationID) AND 
(AgencyLocations.AgencyID = Brokers.AgencyID)) 
ON Carriers.ID = SubmissionLog.WinningCarrierID) 
ON StatusCodes.ID = SubmissionLog.StatusID) 
ON [JILL_MG utah sub query].SubLogID = SubmissionLog.ID) 
ON StatusReasons.StatusReasonID = SubmissionLog.StatusReasonID) 
ON AccountContacts.AccountID = Accounts.ID
WHERE   ( (AccountTypes.Description) Like "prospect" Or (AccountTypes.Description) Like "prev*") 
AND ( (SubmissionLog.EffectiveDate)>#12/31/2010#)  
AND  ((StatusCodes.Description) Like "not*")  
AND ((Accounts.dbType_id) In (15)) )
GROUP BY AccountTypes.Description, AccountContacts.FirstName, 
AccountContacts.LastName,  Accounts.Name, Accounts.StreetAddress, 
Accounts.MailAddress,SubmissionLog.EffectiveDate, 
SubmissionLog.ExpirationDate, StatusCodes.Description
ORDER BY Accounts.Name

它根据帐户名称提供提交详细信息。但我们可以重复帐户名称,因为我们可以为具有不同有效日期的帐户提交许多内容。但在这里我需要修改thr查询,以便我可以获得最近生效日期(具有最大值SubmissionLog.Id)的帐户详细信息,而不管帐户名称与其他列的唯一组合。我希望帐户名称与最近的生效日期一致,这样每个帐户名称只有一行。我已使用MAX(SubmissionLog.Id)进行过滤,但由于与其他列的唯一组合,帐户名称会重复,因为它具有多个与其他列具有不同值的组合。关于这个家伙的任何解决方法...... ??

1 个答案:

答案 0 :(得分:0)

您需要的是一个子查询,它从这三个表中获取数据:

SELECT MAX(SubmissionLog.ID) MaxId, Accounts.Name
FROM 
SubmissionLog 
LEFT JOIN (AccountTypes 
RIGHT JOIN (BusinessTypes 
RIGHT JOIN Accounts ON BusinessTypes.ID = Accounts.BusinessTypeID) 
ON AccountTypes.ID = Accounts.AccountTypeID) 
ON SubmissionLog.AccountID = Accounts.ID
GROUP BY Accounts.Name

然后你可以通过Accounts.Name和SubmissionLog.ID将你的主要查询加入到这个子查询到MaxID,这样你就会获得受最大提交id限制的附加列