July 2, 2010 at 12:31 pm
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.
July 2, 2010 at 12:52 pm
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.
July 2, 2010 at 1:46 pm
Thanks for the help.
July 2, 2010 at 1:57 pm
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
July 2, 2010 at 2:23 pm
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)
July 2, 2010 at 3:18 pm
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
July 5, 2010 at 12:31 pm
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