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
The MONTHNAME() function returns the name of the month for a given date.
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 .
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).
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.
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With