Can I convert a datetime to just a year/month for a group by?

  • I need to group records by the month/year in a select statement, but the field i have to base it off of it a datetime field. Is there a way to convert that to just a month and year for my group by? Thanks.

  • simplest way is to do something like:

    group by (datepart(year,date)*100 ) + datepart(month,date)

    The probability of survival is inversely proportional to the angle of arrival.

  • Thanks for the help.

  • There are lots of variations that will work.

    Here's another that gives you a six-character string in the format YYYYMM.

    SELECT LEFT(CONVERT(VARCHAR,GETDATE(),112),6) as YrMth

    Just substitute your date column for getdate().

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

  • You could also just convert the datetime to the first day of the month at time 00:00:00.000 and group by that:

    group by dateadd(mm,datediff(mm,0,MyDate),0)

  • The Dixie Flatline (7/2/2010)


    There are lots of variations that will work.

    Here's another that gives you a six-character string in the format YYYYMM.

    SELECT LEFT(CONVERT(VARCHAR,GETDATE(),112),6) as YrMth

    Just substitute your date column for getdate().

    Don't need the LEFT here - you can do this:

    SELECT CONVERT(CHAR(6), GETDATE(), 112)

    Jeffrey Williams
    “We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”

    ― Charles R. Swindoll

    How to post questions to get better answers faster
    Managing Transaction Logs

  • So you can. 🙂

    I'll remember that. Thank you, Jeffrey.

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

Viewing 7 posts - 1 through 6 (of 6 total)

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