简体   繁体   中英

MySQL Order by date with GROUP BY DATE FORMAT is alphabetical

This is my query:

Select Date_format(`date`, '%b %Y') as 'Categories',
..... as 'a1',....... as 'a2'
FROM table1
GROUP BY Date_format(`date`, '%b %Y')
ORDER BY Date_format(`date`, '%b %Y') ASC

Answer is alphabetical because, date_format convert date to string, I need sorting by date, but, group by is the problem. I need group by only for Date_format('date','%b %Y')

Please give a solution

Of course it is alphabetical. You are ordering by a string. Try:

ORDER BY MIN(date) ASC

This will order by the date value.

Note that in the original version of your question, you had single quotes around date . That will not order by anything at all, because 'date' is a string with a four letter word in it.

Just do this:

Select Date_format(`date`,'%b %Y') as 'Categories',
..... as 'a1',....... as 'a2'
FROM table1
GROUP BY Date_format(`date`,'%b %Y')
ORDER BY `date` ASC

I solved this question putting double quotes

Select Date_format(`date`, '%b %Y') as 'Categories',
..... as 'a1',....... as 'a2'
FROM table1
GROUP BY Date_format(`date`, '%b %Y')
ORDER BY "categories" ASC

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