选择最大日期范围日期

时间:2013-07-06 10:21:06

标签: ms-access ms-access-2007

我有一张表检查,我正在尝试选择我想要的每个日期范围的最大日期。这是在MS Access 2007查询中,我找到的大多数答案都是T SQL格式。

例如日期范围:介于#1/1/2012#和#3/30/2012#

之间
Date       PlateNo     TickeStatus
01-15-12       A        Open
01-23-12       c        Open
01-17-12       A        Close
02-23-12       c        Open
02-15-12       A        Open
03-23-12       c        Open
03-15-12       A        Close
03-28-12       c        Close
04-15-12       A        Open
04-23-12       c        Close

在我设定的日期范围内。我想要的结果是这样的:

Date       PlateNo     TickeStatus
03-15-12       A        Close
03-28-12       c        Close

1 个答案:

答案 0 :(得分:1)

此查询会为您提供目标日期范围内每个Date的最大PlateNo

SELECT i.PlateNo, Max(i.Date) AS MaxOfDate
FROM inspections AS i
WHERE i.Date BETWEEN #2012-1-1# AND #2012-3-30#
GROUP BY i.PlateNo;

要获取相应的TickeStatus值,请将其用作您加入检验表的子查询。

SELECT i2.Date, i2.PlateNo, i2.TickeStatus
FROM
    inspections AS i2
    INNER JOIN
        (
            SELECT i.PlateNo, Max(i.Date) AS MaxOfDate
            FROM inspections AS i
            WHERE i.Date BETWEEN #2012-1-1# AND #2012-3-30#
            GROUP BY i.PlateNo
        ) AS sub
    ON
            (i2.PlateNo = sub.PlateNo)
        AND (i2.Date = sub.MaxOfDate);