-1

I need to display only the month and year from a Datetime field in SQL Server 2008.

This should be formatted in the following way:

Jan 13
Feb 13
March 13

etc

I also need to group by and order by these results

I've tried many permutations of Cast, Convert, DatePart etc but can't quite get what I need.

Any suggestions?

1
  • If you can upgrade to SQL Server 2012, you would get SELECT FORMAT(GETDATE(), 'MMM yy')
    – marc_s
    Apr 4, 2013 at 15:54

4 Answers 4

3
SELECT MonthYear
FROM (  SELECT  CONVERT(CHAR(6),YourDate,112) MonthYearOrder, 
                CONVERT(CHAR(6),YourDate,107) MonthYear
        FROM YourTable
        GROUP BY CONVERT(CHAR(6),YourDate,112), 
                 CONVERT(CHAR(6),YourDate,107)) A
ORDER BY MonthYearOrder
1

You can use a utility function something like this

Format SQL Server Dates (by Anubhavg)

0
SELECT (left(convert(char(11), date, 107), 3) + " " +
right(convert(char(11), date, 107), 2)) as date from 
(
    select date from yourtable 
    group by date 
    order by year(date) asc, month(date)asc
) as a    

Convert 107 will give you the format MMM dd, yyyy, you only need month and last 2 digits of year so we'll use left function to get MMM and right function to get last 2 digits of year

Update: add support for sorting and grouping. And you can even add where clause into sub query to conditioning

7
  • No I need month and year. 13 being shorthand for 2013 :)
    – coopertkm
    Apr 4, 2013 at 14:52
  • Answer edited, please try it and tell me whether it's useful for you or not :D
    – Doan Cuong
    Apr 4, 2013 at 15:00
  • I'm trying to get the Group By and Order By functionality working with this now! I need to group my results by each month and have this in ascending order.
    – coopertkm
    Apr 4, 2013 at 15:08
  • so just user group by (left(convert(char(11), date, 107), 3) + " " + right(convert(char(11), date, 107), 2)) and order by Year(date) ASC, Month(Date) ASC. I think it'll work, but you better test it first :D
    – Doan Cuong
    Apr 4, 2013 at 15:09
  • I'm afraid that gives me the dreaded: Column "datecolumn" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause. That message has been the bane of my existence today!
    – coopertkm
    Apr 4, 2013 at 15:16
0

I would try this :

select convert(char(3), yourdatefield, 0) + " " + (YEAR( yourdatefield ) % 100) from yourtable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.