Click here to Skip to main content
15,896,359 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a table in which a column has month like this.


jan-14
feb-14
mar-14
aug-14
apr-14
dec-14
nov-14


I want to select max month (for ex. dec-14) how ?
Posted

I am not going into detail of your table schema because you know the best design for your data. But I would not store the date as string in first place.

Anyway, you could do some string manipulation and have a query something like this:

SQL
SELECT
    SUBSTRING (Months, 0 , 4) AS Month,
    CONVERT(INT, SUBSTRING (Months, 5 , 9)) AS Year,
    Month(SUBSTRING (Months, 0 , 4) + ' 12 2014') AS MonthNumber
FROM
    CP
ORDER BY
    Year DESC, MonthNumber DESC


After this you can use MAX, TOP etc. to what you want!
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 18-Sep-14 14:04pm    
5ed.
—SA
How about this:

SQL
DECLARE @mon VARCHAR(32) = 'sep-14'
PRINT DATEPART(m , CONVERT(date, '1-' + @mon , 6))



And please don't store dates as strings.
 
Share this answer
 
Comments
Manas Bhardwaj 18-Sep-14 11:48am    
Yes, this would work +5!
Sergey Alexandrovich Kryukov 18-Sep-14 14:04pm    
5ed, especially for the last statement. :-)
—SA
Hi,

SQL
SELECT TOP 1 CONVERT(DATETIME, '01-'+ ColumnName , 106) AS ColumnDate
ORDER BY ColumnDate DESC



Thanks,
Baliram Suryawanshi
 
Share this answer
 
v2
SQL
SELECT substring(convert(varchar(20), max(convert(DATETIME,'1-'+month)), 6), 4, 20)  FROM TableName
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900