Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql - order by monthname

I am trying to order mysql query by month name like:

January --  5
February -- 2
March    -- 5
and so on

Here is my query, but its not ordering:

SELECT leave_balance.balance, MonthName(leave_balance.date_added) AS month 
FROM leave_balance WHERE leave_balance.staff_id_staff = $iid 
GROUP BY month,  leave_balance.leave_type_id_leave_type 
HAVING leave_balance.leave_type_id_leave_type = $leaveBalTypID 
ORDER BY month

Kindly tell me where I am doing wrong

like image 368
user007 Avatar asked Mar 25 '13 04:03

user007


People also ask

What does Monthname function do in MySQL?

The MONTHNAME() function returns the name of the month for a given date.

Can we use ORDER BY before group by in MySQL?

ORDER BY has to come after GROUP BY . But if we GROUP BY first, we run into the same issue above with the MAX function and, depending on your MySQL version, ONLY_FULL_GROUP_BY mode .

Can we use 2 ORDER BY in MySQL?

If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query. After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary).

How do I sort by alphabetical order in MySQL?

Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order.


2 Answers

you can specify like

ORDER BY FIELD(MONTH,'January','February','March',...)


SELECT leave_balance.balance, MonthName(leave_balance.date_added) AS month 
FROM leave_balance WHERE leave_balance.staff_id_staff = $iid 
GROUP BY month,  leave_balance.leave_type_id_leave_type 
HAVING leave_balance.leave_type_id_leave_type = $leaveBalTypID 
ORDER BY FIELD(MONTH,'January','February','March',...,'December');
like image 70
PSR Avatar answered Sep 25 '22 02:09

PSR


Just add this at the end of your query statement:

ORDER BY str_to_date(MONTH,'%M')

If column name changes in the future you will not need to worry about it.

like image 21
Masood Avatar answered Sep 24 '22 02:09

Masood