Access query with dates

  • Hi guys!

    I have a table with some fiels, including amount, month and year.

    What I'm trying to do is a query that reports the following:

    select the amount from table where month is previous to the one we're on, including years

    Is it possible?

    Thanks allot

  • use this condition

    WHERE MonthColumn = MONTH(DATEADD(m, -1, GETDATE())) AND YearColumn YEAR(DATEADD(m, -1, GETDATE()))

    Regards,
    Nitin

  • Hi nitinpatel31 and thx for the fast reply

    I had to change the condition to:

    WHERE MonthColumn = MONTH(DATEADD(m, -1, NOW())) AND YearColumn YEAR(DATEADD(m, -1, NOW()))

    still the results are only for the one month before NOW() and I need all:

    for example:

    lets say the oldest record is from 01/01/2008, the query has to return all records from that date until today 29/01/2009 (NOW())

    Any ideas?

  • Do you store date (as Date/SmallDate type) in single column or have seperate column for month and year?

    Regards,
    Nitin

  • If you have single column for date field you can use below contition

    WHERE DateColumn < CAST((CAST(YEAR(GETDATE()) AS VARCHAR) + '/' + CAST(MONTH(GETDATE()) AS VARCHAR) + '/01' ) AS DATE)

    This will select all records, except current month.

    Regards,
    Nitin

  • If you store month (monthColumn) and year (yearColumn) in different column then use below condition

    WHERE CAST((CAST(YearColumn AS VARCHAR) + '/' + CAST(MonthColumn AS VARCHAR) + '/01') AS DATE)

    <= CAST((CAST(YEAR(DATEADD(m, -1, GETDATE())) AS VARCHAR) + '/' + CAST(MONTH(DATEADD(m, -1, GETDATE())) AS VARCHAR) + '/01' ) AS DATE)

    Regards,
    Nitin

  • yes, they are diferent columns for each value. will try the last solution and post a reply in few

    thx

  • I think CAST() isn't available on ACCESS

    Maybe CONVERT()? I'm trying to redo your solution using it

  • Yes CAST and GETDATE are sql server function. But you can findout similar function for Access.

    Regards,
    Nitin

  • Pedro,

    You can use this in your query to convert each month / year to the 1st day of the month / year:

    DateSerial([YearField],[MonthField],1)

    That function returns a date, so you could use

    WHERE DateSerial([YearField],[MonthField],1) < Now()

    however, if that also returns unwanted records from the current month, you might have to use this:

    WHERE DateSerial([YearField],[MonthField],1) < DateSerial(Year(Now()),Month(Now()),1)

  • Thanks allot William, that was just what I needed

    Peace

Viewing 11 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic. Login to reply