Ms Access - 加入两个表并获取最后一条记录

时间:2015-07-23 19:03:08

标签: sql ms-access

我有2个名为Reefers和FilteredAlerts的表。我想加入这两个表。

如何获取Status =' Loaded'的每个冷藏箱的最后一条记录。和GPSAlertype ='温度'?

enter image description here

正如您在结果中看到的那样,ReeferNo R-3未显示,因为GPSAlertType不等于Temperature。我使用下面的代码,但总是给我一个错误。

 SELECT
   r.ReeferNo,
   r.TransporterName,
   r.Status, 
   sub2.AlertDateTime,
   sub2.ReceivedDateTime,
   sub2.GPSAlertType,
   sub2.Temperature,
   sub2.Location
FROM
   Reefers AS r
   LEFT JOIN
   (
      SELECT
         sub1.ReeferNo,
         a2.AlertDateTime,
         a2.ReceivedDateTime,
         a2.GPSAlertType,
         a2.Temperature,
         a2.Location
     FROM
         (
             SELECT
                 a1.ReeferNo,
                 Max(a1.AlertDateTime) AS MaxOfAlertDateTime
             FROM FilteredAlerts AS a1
             WHERE a1.GPSAlertType='Temperatures' AND r.Status = 'Loaded'
             GROUP BY a1.ReeferNo
         ) AS sub1
         INNER JOIN FilteredAlerts AS a2
         ON
                (sub1.MaxOfAlertDateTime = a2.AlertDateTime)
            AND (sub1.ReeferNo = a2.ReeferNo)
     ) AS sub2
 ON r.ReeferNo = sub2.ReeferNo;

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

你在这里:

SELECT
    r2.ReeferNo,
    r2.TransporterName,
    r2.Status,
    a2.AlertDateTime,
    a2.ReceivedDateTime,
    a2.GPSAlertType,
    a2.Temperature,
    a2.Location
FROM ((SELECT r.ReeferNo, Max(a.AlertDateTime) as AlertDateTime
    FROM Reefers r LEFT JOIN FilteredAlerts a ON r.ReeferNo = a.ReeferNo
    WHERE
        r.Status="Loaded" AND 
        a.GPSAlertType='Temperature'
    GROUP BY r.ReeferNo
) s LEFT JOIN FilteredAlerts a2 ON 
    s.ReeferNo = a2.ReeferNo and
    s.AlertDateTime = a2.AlertDateTime
) INNER JOIN Reefers r2 ON s.ReeferNo = r2.ReeferNo
WHERE a2.GPSAlertType='Temperature' and
    r2.Status='Loaded';