简体   繁体   中英

MYSQL ordering by date (string)

I have a date column which is formatted like this: 28-15 .

The format for this is the first number tells which week, and the second one which year.

I have tried using str_to_date(datecolumn, '%v-%y') with no good results. It orders the list BUT its not in the correct order.

I also tried concatting the datecolumn to make the string appear like this:

01-28-15 (First is the day of the week) and using str_to_date(datecolumn, '%w-%v-%y) , with no luck.

What am I doing wrong?

From MySql docs :

You cannot use format "%X%V" to convert a year-week string to a date because the combination of a year and week does not uniquely identify a year and month if the week crosses a month boundary. To convert a year-week to a date, you should also specify the weekday:

SELECT STR_TO_DATE('200442 Monday', '%X%V %W');    

For you case, you need to make assumptions about week day(for example monday) and century(for example 2000), then you can get date next way:

SELECT DATE_ADD(STR_TO_DATE(CONCAT(datecolumn, ' ', 'Monday'), '%V-%X %W'), INTERVAL 2000 YEAR)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM