SQL Order By month name 按时间顺序而不是字母顺序

SQL Order By month name chronologically instead of alphabetically

我想让月份名称按时间顺序排列,而不是按字母顺序排列。 这是我的 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

我希望它是:

January

February

March

...

...

你可以利用温度 table

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

按月份排序即可。 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'))

如果您正在使用 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(month + ' 1 2014')