sql >> データベース >  >> RDS >> Mysql

月ごとにグループ化し、特定の月に値がない場合にゼロを返す方法は?

    すべての月の表を作成してから、left join あなたのテーブルへ:

    SELECT MONTHNAME(m.month) AS mName, 
        MONTH(m.month) AS mOrder, 
        ifnull(sum(amount),0) AS total_num 
    from months m
    left join income i
    on m.month = i.date
    
    GROUP BY mOrder 
    ORDER BY mOrder DESC
    

    monthsを作成したくない場合 次に、次のことができます。

    (select STR_TO_DATE('01/01/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/02/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/03/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/04/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/05/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/06/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/07/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/08/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/09/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/10/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/11/2016', '%d/%m/%Y') as month union 
     select STR_TO_DATE('01/12/2016', '%d/%m/%Y') as month)
    


    1. 簡略化:mysqlinum_rowsが機能しない

    2. 正規表現str_replace

    3. ユキヒョウにmysqldbをインストールする

    4. Oracle11gでシーケンスをリセット