简体   繁体   中英

Access query to pull previous month's data

I have a table in Access 2013 (Table1) that contains the following columns:

ID (pk), ReportDate, Amount

The most current data is 30-50 days old. For example, today (6/22/16) the most recent data would be the 5/1/16 row, as the 6/1/16 data won't be entered until mid-July. (All dates in the ReportDate column are the 1st of the month, ie: 4/1/16, 5/1/16, etc.)

I need to write a query that will do a 6-month lookback, but exclude the most current month's data.

So, for example, if I ran the query today (6/22/16), I would only get the rows that correspond to the following months:

12/1/2015
 1/1/2016
 2/1/2016
 3/1/2016
 4/1/2016

The data for 5/1/16 should be excluded, as it's the most recent month.

I can pull the previous 6 months worth of data with setting the criteria (in QBE) for ReportDate to >=DateAdd("m",-6,Date()) , but I can't seem to figure out how to exclude the most recent month.

This should give you the start date of the most recent month in your table:

SELECT Max(ReportDate) AS MaxOfReportDate
FROM Table1;

If that is the month you want to exclude, use that query as a subquery which you cross join back to the table. Then you can use a WHERE clause with a BETWEEN condition whose end points are determined by DateAdd() expressions based on MaxOfReportDate :

SELECT t.ID, t.ReportDate, t.Amount
FROM
    Table1 AS t,
    (
        SELECT Max(ReportDate) AS MaxOfReportDate
        FROM Table1
    ) AS sub
WHERE
    t.ReportDate BETWEEN DateAdd('m', -6, sub.MaxOfReportDate)
                     AND DateAdd('m', -1, sub.MaxOfReportDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM