user5893513
user5893513

Reputation:

How to sort an SQL table/view by month and year?

I have SQL table/view which has a column called "Month".The way data is displayed in this column "MonthName" + "Year"."SQL TABLE".I want to know if there is way to sort this by year and month ? I tried the "Order by Month" but that only sorts it alphabetically.

Upvotes: 0

Views: 556

Answers (3)

Matt Spinks
Matt Spinks

Reputation: 6698

You can use the CONVERT function on your [Month] column (Month + Year). That will convert each value to a DATE object corresponding to the first day of the month/year. Then do a sort on that:

SELECT
 *
FROM
 MyTable
ORDER BY
 CONVERT(DATE,[Month])

Upvotes: 3

Jeffrey
Jeffrey

Reputation: 538

I would use a date field and sort by that. You can use:

concate(DATENAME(month,MyDateField), " ", YEAR(MyDateField))

In a view, query, or a persisted computed column depending on what works best for you.

Upvotes: 0

Wilium
Wilium

Reputation: 1

You can convert colum ("Monnth" "Year") to DATE TYPE and order by DATE colum

SELECT
     TO_DATE('August 2017'
            ,'Month YYYY')
 FROM DUAL;

Upvotes: 0

Related Questions