我正在尝试根据月份名称订购一个mysql查询,但它按相反的顺序排序。我已经尝试了ASC和DESC订单但没有工作!这就是我得到的:
order_amount month_number
370.245 Dec
0.01 Aug
0.02 July
0.01 May
2 Apr
3 Mar
4 Feb
5 Jan
这是查询:
select sum(amnt) as order_amount,month_number from orders where paid =1 GROUP BY month_number ORDER BY MONTH(month_number) ASC
这是我正在运行查询的示例表'order'
order_amount month_number paid
370.245 Jan 1
0.01 Aug 1
0.02 July 1
0.01 Apr 1
2 May 0
3 Mar 1
4 Feb 0
5 Nov 0
答案 0 :(得分:1)
month_number()
是该月份字符串名称的糟糕名称。也就是说,您的尝试无效,因为month()
需要一个日期,而不是字符串表示。最好的方法可能只是使用case
:
order by (case when month_number = 'Jan' then 1
when month_number = 'Feb' then 2
. . .
when month_number = 'Dec' then 12
end)
我强烈建议您在表格中包含日期或实际月份编号。并且,将month_number
重命名为month_name
。
答案 1 :(得分:0)
根据您的示例,您在month_number
字段中已经' Dec'' 8月' 等等。
如果您没有通过有效的日期类型,month(month_number)
如何运作?如果您传递了一些随机文字,那么您只需获得NULL
并且无法按NULL
http://sqlfiddle.com/#!2/3a774d/3/0
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month
答案 2 :(得分:0)
SELECT * FROM my_table;
+-------+
| month |
+-------+
| Apr |
| Aug |
| Dec |
| Feb |
| Jan |
| Jul |
| Jun |
| Mar |
| May |
| Nov |
| Oct |
| Sep |
+-------+
SELECT * FROM my_table ORDER BY STR_TO_DATE(CONCAT('2014-',month,'-01'),'%Y-%b-%d');
+-------+
| month |
+-------+
| Jan |
| Feb |
| Mar |
| Apr |
| May |
| Jun |
| Jul |
| Aug |
| Sep |
| Oct |
| Nov |
| Dec |
+-------+
......或类似的东西