2017-05-31 115 views
0

我希望按月份顺序排列月份名称,而不是按字母顺序排列。 这是我的Sql代码。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

我想它是:

.. 。

...

+0

选择'terms'过在你的子查询,然后以通过它 –

+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')) 
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 
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')