MySQL Order Previous 6 Months In Reverse

134 Views Asked by At

I have the below MySQL query that outputs months and SUM of value properly but I want to order the date for the previous 6 months data in reverse rolling format so it would be Feb, Jan, Dec, Nov, Oct, Sep. However this range will change every month so not sure that field() function would apply in an ORDER BY?

SELECT month(c.date) AS month_num, monthname(c.date) AS month, SUM(value) AS total
FROM commissions c
WHERE c.date BETWEEN CURDATE() - INTERVAL 7 MONTH AND CURDATE()
GROUP BY month(c.date)

Result:

| month_num | month     | total   | 
|-----------|-----------|---------|
| 1         | January   | 45198   | 
| 2         | February  | 95661   | 
| 9         | September | 8373    |
| 10        | October   | 5356    |
| 11        | November  | 4745    |
| 12        | December  | 4830    |

Need this to be reverse rolling format Feb, Jan, Dec, Nov, Oct, Sep. Thoughts?

1

There are 1 best solutions below

0
Widada On BEST ANSWER

I think this is will help

SELECT month(c.date) AS month_num, monthname(c.date) AS month, SUM(value) AS 
total
FROM commissions c
WHERE c.date BETWEEN CURDATE() - INTERVAL 7 MONTH AND CURDATE()
GROUP BY month(c.date)
ORDER BY c.date DESC