I have a mysql table with month and year in same field as below.
+----------------+
| duedate |
+----------------+
| Sept '12 |
| Oct '12 |
| Nov '12 |
| May'13 |
| Mar'13 |
| Mar '13 |
| Jan '13 |
| Feb '13 |
| Dec '12 |
| Aug '12 |
| Apr '13 |
+----------------+
I want to retrieve this table by sorting month and year values in DESC order as below.
+------------+
| duedate |
+------------+
| May'13 |
| Apr '13 |
| Mar '13 |
| Mar'13 |
| Feb '13 |
| Jan '13 |
| Dec '12 |
| Nov '12 |
| Oct '12 |
| Sept '12 |
| Aug '12 |
+------------+
Is it possible to sort as above.. I have tried below sql query but it sorts the data by DESC of year values only, month sorting is not working..
"SELECT DISTINCT duedate FROM sample_table ORDER BY substr(duedate, -2) DESC, FIELD(duedate, 'Dec', 'Nov', 'Oct', 'Sep', 'Aug', 'Jul', 'Jun', 'May', 'Apr', 'Mar', 'Feb', 'Jan')"
Please help..
You should store the date in a DATE
type and not in a VARCHAR
or a CHAR
as it seems you are doing.
In that case you could very simple retrieve the data in the order you want just using the ORDER BY
in this way:
select * from YOURTABLE order by date asc
If for any reason you can not change this, I would recommend you to add another column in your table (called read_date
for example), and then just update your table with something like:
update table YOURTABLE set real_date = date
That would add the correct value to the column and you would be able to work properly with dates.
If you still don't want to do this, you can always cast the data and force it to be read as a date using the STR_TO_DATE function like this:
SELECT * FROM YOURTABLE ORDER BY STR_TO_DATE(date, '%b %y') DESC;
More information about Mysql date formats here .
It's not particularly easy to sort this data as it is seen by the database as text which will be sorted alphanumerically rather than in date order.
The best solution would be to add month and year fields and store the values as integers then output the string value using PHP date() formatting. You could then order by integer exactly how you want
Alternatively you can use the FIELD
keyword in your query to sort on, however this isn't the best way to do it
SELECT * FROM YOURTABLE ORDER BY FIELD(duedate, 'May 13', 'Jun 13', 'Jul 13', ....)
you can try like this-
SELECT STR_TO_DATE(duedate,'%M \'%Y') as due FROM demo ORDER BY due DESC
I am not sure but try with str_to_date in mysql
See dem link: SQLFIDDLE
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.