SQL Order按月按时间顺序而不是按字母顺序排列

时间:2017-05-31 13:36:58

标签: mysql sql phpmyadmin sql-order-by

我想让月份名称按时间顺序排列,而不是按字母顺序排列。 这是我的Sql代码。

SELECT month, sum(total) 
FROM (SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) AS total  
      FROM projects 
      WHERE terms >= '2017/01/01'
      GROUP BY MONTH(terms) 
      UNION 
      SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) AS total 
      FROM archive
      WHERE terms >= '2017/01/01' 
      GROUP BY MONTH(terms) 
     ) AS test
GROUP BY month
ORDER BY month

上面代码的输出看起来像This

我希望它是:

  

一月

     

二月

     

三月

     

...

     

...

3 个答案:

答案 0 :(得分:1)

将月份命令为int以进行订购。 With MONTH(STR_TO_DATE(month, '%M'))

SELECT month, sum(total) 
    FROM (SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) AS total  
          FROM projects 
          WHERE terms >= '2017/01/01'
          GROUP BY MONTH(terms) 
          UNION 
          SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) AS total 
          FROM archive
          WHERE terms >= '2017/01/01' 
          GROUP BY MONTH(terms) 
         ) AS test
    GROUP BY month
    ORDER BY MONTH(STR_TO_DATE(month, '%M'))

答案 1 :(得分:0)

您可以利用临时表

with temp as(
SELECT month, sum(total) as total
FROM (SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) AS total  
      FROM projects 
      WHERE terms >= '2017/01/01'
      GROUP BY MONTH(terms) 
      UNION 
      SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) AS total 
      FROM archive
      WHERE terms >= '2017/01/01' 
      GROUP BY MONTH(terms) 
     ) AS test
GROUP BY month
)
select * from temp order by month

答案 2 :(得分:0)

如果您正在使用SQL Server数据库:

SELECT month, sum(total) 
FROM (SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) AS total  
      FROM projects 
      WHERE terms >= '2017/01/01'
      GROUP BY MONTH(terms) 
      UNION 
      SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) AS total 
      FROM archive
      WHERE terms >= '2017/01/01' 
      GROUP BY MONTH(terms) 
     ) AS test
GROUP BY month
ORDER BY month(month + ' 1 2014')