访问:将子查询集成到excisting Query中

时间:2015-09-17 05:05:00

标签: sql ms-access

我正在使用的查询中的“最后”功能(第4行和第5行)并不完全是我所追求的。最后一个函数查找该表中的最后一条记录。

根据日期字段,我需要找到的是表格中的最新记录。

SELECT
        tblinmate.statusid,
        tblinmate.activedate,
        Last(tblclassificationhistory.classificationid) AS LastOfclassificationID,
        Last(tblsquadhistory.squadid) AS LastOfsquadID,
        tblperson.firstname,
        tblperson.middlename,
        tblperson.lastname,
        tblinmate.prisonnumber,
        tblinmate.droppeddate,
        tblinmate.personid,
        tblinmate.inmateid
FROM tblsquad
INNER JOIN (tblperson
INNER JOIN ((tblinmate
INNER JOIN (tblclassification
INNER JOIN tblclassificationhistory
        ON tblclassification.classificationid =
        tblclassificationhistory.classificationid)
        ON tblinmate.inmateid =
        tblclassificationhistory.inmateid)
INNER JOIN tblsquadhistory
        ON tblinmate.inmateid =
        tblsquadhistory.inmateid)
        ON tblperson.personid = tblinmate.personid)
        ON tblsquad.squadid = tblsquadhistory.squadid
GROUP BY tblinmate.statusid,
         tblinmate.activedate,
         tblperson.firstname,
         tblperson.middlename,
         tblperson.lastname,
         tblinmate.prisonnumber,
         tblinmate.droppeddate,
         tblinmate.personid,
         tblinmate.inmateid;

下面的查询就是这样,根据日期字段查找表中的最新记录。

我的问题是我不知道如何将此查询集成到上面以替换“最后”功能

SELECT a.inmateID,
       a.classificationID,
       b.max_date
FROM (
    SELECT tblClassificationHistory.inmateID, 
           tblClassificationHistory.classificationID,                
           tblClassificationHistory.reclassificationDate
    FROM tblinmate
    INNER JOIN tblClassificationHistory
    ON tblinmate.inmateID = tblClassificationHistory.inmateID 
) a
INNER JOIN (
    SELECT tblClassificationHistory.inmateID, 
           MAX(tblClassificationHistory.reclassificationDate) as max_date
    FROM tblinmate
    INNER JOIN tblClassificationHistory
    ON tblinmate.inmateID = tblClassificationHistory.inmateID
    GROUP BY tblClassificationHistory.inmateID  
) b
ON a.inmateID = b.inmateID
AND a.reclassificationDate = b.max_date
ORDER BY a.inmateID;

1 个答案:

答案 0 :(得分:-1)

我从另一个论坛得到了一个提示,可以将这样的查询结合起来

SELECT qryMainTemp.*, qrySquad.*, qryClassification.*
FROM (qryMainTemp INNER JOIN qrySquad ON qryMainTemp.inmateID = qrySquad.inmateID) INNER JOIN qryClassification ON qryMainTemp.inmateID = qryClassification.inmateID;

并且它有效:)我将第一个查询分成两个查询,然后组合上面显示的三个查询。

可悲的是,这又引发了另一个问题,即查询现在没有up-datable ..正在为此解决方案