Select Max Date by Date Range

拥有回忆 提交于 2019-12-11 12:42:38

问题


I have a table Inspection and I'm trying to select the max date per date range I want. This is in MS Access 2007 query and most answers I found is in T SQL format.

For example Date Range: Between #1/1/2012# AND #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

In the date range I set. the result I want is like this:

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

回答1:


This query will give you the maximum Date for each PlateNo within your target date range.

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;

To get the corresponding TickeStatus values, use that as a subquery which you join to the inspections table.

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);


来源:https://stackoverflow.com/questions/17501975/select-max-date-by-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!