我有2个名为 Reefers 和 Alerts 的表。我想加入这两个表。
现在,如何从警报类型等于警报表中获取显示每个 ReeferNo 的最后记录的结果> “温度”?
TABLE 1: Reefers
ReeferNo Transporter
E-110 Express1
E-111 Express1
E-112 Express1
A-001 A-Trucking
A-002 A-Trucking
TABLE 2: Alerts
AlertDateTime ReceivedDateTime AlertType ReeferNo Temperature Location
5/2/15 9:53 AM 5/2/15 9:58 AM Arrival E-110 5.2 Warehouse
5/2/15 9:48 AM 5/2/15 9:53 AM Departure E-111 5.4 Warehouse
5/2/15 9:40 AM 5/2/15 9:45 AM Temperatures A-001 11.37 Warehouse
5/2/15 9:38 AM 5/2/15 9:43 AM Temperatures A-001 10.06 Store
5/2/15 9:35 AM 5/2/15 9:40 AM Temperatures A-001 10.02 Store
5/2/15 9:19 AM 5/2/15 9:24 AM Departure A-001 10.02 Store
5/2/15 9:12 AM 5/2/15 9:17 AM Temperatures A-002 10.37 Warehouse
5/2/15 9:06 AM 5/2/15 9:11 AM Temperatures A-002 12.62 Warehouse
5/2/15 9:04 AM 5/2/15 9:09 AM Arrival A-002 12.62 Warehouse
结果必须是:
ReeferNo Transporter AlertDateTime ReceivedDateTime AlertType Temperature Location
E-110 Express1
E-111 Express1
E-112 Express1
A-001 A-Trucking 5/2/15 9:40 AM 5/2/15 9:45 AM Temperatures 11.37 Warehouse
A-002 A-Trucking 5/2/15 9:12 AM 5/2/15 9:17 AM Temperatures 10.37 Warehouse
我正在使用下面的代码,但它没有给我我想要的结果。
SELECT Reefers.ReeferNo, Reefers.Transporter, Alerts.AlertType,
Alerts.AlertDateTime, Alerts.Temperature, Alerts.Location,
Alerts.ReceivedDateTime
FROM Reefers INNER JOIN (Alerts INNER JOIN (SELECT
Alerts.ReeferNo,
MAX(Alerts.ReceivedDateTime)
AS MaxReceivedDateTime
FROM Alerts
GROUP BY Alerts.ReeferNo) AS temptable ON (Alerts.ReeferNo =
temptable.ReeferNo) AND (Alerts.ReceivedDateTime =
temptable.MaxReceivedDateTime)) ON Reefers.ReeferNo = Alerts.ReeferNo
WHERE (((Alerts.AlertType)="Temperatures"));
更新:
我改变了所需的结果。而不是单词Null,将 Reefers 留空,不带温度 AlertType 。
答案 0 :(得分:0)
从一个查询开始,该查询为那些至少有一个温度警报的冷藏箱提供了所需的一切:
SELECT
sub1.ReeferNo,
a2.AlertDateTime,
a2.ReceivedDateTime,
a2.AlertType,
a2.Temperature,
a2.Location
FROM
(
SELECT
a1.ReeferNo,
Max(a1.AlertDateTime) AS MaxOfAlertDateTime
FROM Alerts AS a1
WHERE a1.AlertType='Temperatures'
GROUP BY a1.ReeferNo
) AS sub1
INNER JOIN Alerts AS a2
ON
(sub1.MaxOfAlertDateTime = a2.AlertDateTime)
AND (sub1.ReeferNo = a2.ReeferNo);
然后LEFT JOIN
将基于第一个查询的 Reefers 表添加到子查询...
SELECT
r.ReeferNo,
r.Transporter,
sub2.AlertDateTime,
sub2.ReceivedDateTime,
sub2.AlertType,
sub2.Temperature,
sub2.Location
FROM
Reefers AS r
LEFT JOIN
(
SELECT
sub1.ReeferNo,
a2.AlertDateTime,
a2.ReceivedDateTime,
a2.AlertType,
a2.Temperature,
a2.Location
FROM
(
SELECT
a1.ReeferNo,
Max(a1.AlertDateTime) AS MaxOfAlertDateTime
FROM Alerts AS a1
WHERE a1.AlertType='Temperatures'
GROUP BY a1.ReeferNo
) AS sub1
INNER JOIN Alerts AS a2
ON
(sub1.MaxOfAlertDateTime = a2.AlertDateTime)
AND (sub1.ReeferNo = a2.ReeferNo)
) AS sub2
ON r.ReeferNo = sub2.ReeferNo;