使用逐月分组从1月到12月排序

时间:2012-04-11 09:16:12

标签: mysql sql group-by

我写了查询

SELECT 
    MONTHNAME( create_date ) AS MONTH, 
    COUNT( dollar_value_awarded ) AS monthly_sales_count 
FROM claims 
WHERE spiffid='$id' 
AND create_date BETWEEN '$sdate' AND '$edate' 
GROUP BY MONTH

并显示

MONTH     monthly_sales_count
April       285
February    134
March       958

我希望它显示如下:

MONTH     monthly_sales_count
February    134
March       958
April       285

这意味着结果应该从1月到12月排序

4 个答案:

答案 0 :(得分:1)

SELECT MONTHNAME( create_date ) AS month_name,             --- change this alias
       COUNT( dollar_value_awarded ) AS monthly_sales_count 
FROM claims 
WHERE spiffid = '$id' 
  AND create_date BETWEEN '$sdate' AND '$edate' 
GROUP BY MONTH(create_date)                         --- use the MONTH() function

答案 1 :(得分:0)

我认为你可以传递MONTH(create_date)作为ORDER BY参数:

SELECT MONTHNAME( create_date ) AS MONTH , COUNT( dollar_value_awarded ) AS monthly_sales_count 
FROM claims WHERE spiffid='$id' and create_date 
BETWEEN '$sdate' AND '$edate' 
GROUP BY MONTH
ORDER BY MONTH(create_date) 

答案 2 :(得分:0)

你可以做到

SELECT MONTHNAME( create_date ) AS MONTH, 
       COUNT( dollar_value_awarded ) AS monthly_sales_count 
  FROM claims 
 WHERE spiffid='$id' and create_date BETWEEN '$sdate' AND '$edate' 
 GROUP BY MONTH, MONTH(create_date)
 ORDER BY MONTH(create_date)

答案 3 :(得分:0)

简单地添加一个ORDER BY子句:

SELECT MONTHNAME( create_date ) AS MONTH , COUNT( dollar_value_awarded ) AS monthly_sales_count      
FROM claims 
WHERE   spiffid='$id' and create_date BETWEEN '$sdate' AND '$edate' 
GROUP BY MONTH 
ORDER BY MONTH(create_date)