0

A table exists which stores month name in the form of string.. I want to order by year and month so as to get proper result.

year(string)  Month(string)  data
------------  ------------   ----
2012           August        bigbox
2012           December      samllbox
2013           April         samll box
2012           September     larg

I want to order by year and month. as in 2012,2013... Jan,feb,march....

I am aware of the method of case statement when Month = 'january' THEN 1 Month - FEB THEN 2

But i do'nt want to use this as the procedure will be too big..

Mosty Mostacho
  • 42,742
  • 16
  • 96
  • 123
user2637506
  • 215
  • 5
  • 10
  • 19
  • 5
    You should have thought on that before selecting `string` as your data type. You can look for a function in your DBMS and see how that could be handled. – Mosty Mostacho Oct 11 '13 at 13:53
  • If you can change the layout of your table, you should really use a datetime column, it's so much easier to use (ORDER BY datetime DESC) is all you need. – Kevin Oct 11 '13 at 13:54

2 Answers2

3

Your best option is to use the proper date type. Otherwise, create a table (inline or physical) to map your string months.

SELECT 1 AS month, 'January' AS strMonth
UNION ALL
SELECT 2, 'February'
UNION ALL
SELECT 3, 'March'
...
SELECT 12, 'December'

Then map this your table. See a demo

Kermit
  • 33,827
  • 13
  • 85
  • 121
1
SELECT * 
FROM TABLE
ORDER BY [year] DESC,
         DATEPART(month,[Month] + ' 01 ' + CONVERT(VARCHAR(4),[YEAR]))

The above code will give you what you want , but i would strongly suggest you reconsider your design.

Right now you are reserving a string type field which would be at least 15 characters long. This field does not have any value than for display reasons. You could have a DATETIME field that would be much easier to short by (not having to do calculations there) and if you would like to display the name of the month you could use:

DATENAME ( month, DateField )
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69