2017-05-31 5 views
0

アルファベット順ではなく、時系列で月名を取得したいと考えています。 ここに私のSQLコードです。SQL Orderアルファベット順ではなく年代順に

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のように上記のコードの出力はなります

1月

2月

.. 。

...

+0

をあなたのサブクエリにすぎ 'terms'を選択し、それによって順序 –

+0

私はこれを使用し、それが働きました –

答えて

1

注文月を活用することができます。 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

あなたは一時テーブルにそれを注文するintとして

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') 
関連する問題