Reputation: 507
I have a data which is
Monthyear (varchar) Value
Jan 2019 55
Feb 2019 66
Jan 2020 78
Feb 2020 45
when i select the above statement as
select * from datatable order by Monthyear
the result is actually giving me
Monthyear (varchar) Value
Feb 2019 66
Feb 2020 45
Jan 2019 55
Jan 2020 78
But I want it in the month year order. How do I resolve this?
Upvotes: 2
Views: 908
Reputation: 1269493
You should store the "month-year" either as a date (first date of the month) or using a string that is sortable ("2019-01").
However, SQL Server is pretty good at converting strings to dates, so you can use:
order by convert(date, MonthYear)
This will convert by the date that you want.
Actually, you might want to add this to the table. Say:
alter table datatable add yyyymm as (convert(date, MonthYear));
You can even persist this and add an index, if you have a lot of data in the table.
Upvotes: 3