need query help - need to get prior rolling 6 months from today's date

  • This is starting to drive me to drink!!

    I have my date field in my table as [201206], I'm able to get it returned to me as 12 Sept, however I want it returned to me as Sept - 12, PLUS only return the past rolling 6 months from my table so I see it [Jun- 12]

    here is my query:

    SELECT top 10 CONVERT(VARCHAR(6), CONVERT(DATETIME, CONVERT(VARCHAR(6), UsagePeriod) + ' '), 113) as RollingSix

    from monthlyUsage

    key points:

    I need the date format to be as [Jun-12]

    I need to get rolling 6 months from today's date, so I should be able to see date from June 11 to May 12, in essence its the past 11 months, but the requirements has it listed as rolling 6 months

    what am I missing?

  • You should be able to figure it out from this:

    SELECT x.months, [YYYYMM] = CAST(CONVERT(CHAR(6),Months,112) AS INT)

    FROM (VALUES (0),(1),(2),(3),(4),(5),(6)) r (n)

    CROSS APPLY (SELECT Months = DATEADD(mm,-n,GETDATE())) x

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

  • @celko,

    [Okay, here is your problem; you have no idea what you are doing]

    you need to take a pill there buddy, your no genuis

    [You did not define how to compute six month periods]

    6 months is 6 months, there is no extra month because of leap year,

    the date is stored yyyymm, example: 201212 [2012 - 12/December]

    the reports may overlap, they currenly do when the MS Access app that is producing these reports runs monthly

Viewing 3 posts - 1 through 2 (of 2 total)

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