SQL grouping by month and year

后端 未结 9 1658
旧时难觅i
旧时难觅i 2020-11-27 15:57

I\'m not sure what should I write in the following SQL query to show \'date\' column like this: \"month-year\" - \"9-2011\".

SELECT MONTH(date) + \'.\' + YE         


        
相关标签:
9条回答
  • 2020-11-27 16:27

    You can try multiplication to adjust the year and month so they will be one number. This, from my tests, runs much faster than format(date,'yyyy.MM'). I prefer having the year before month for sorting purpose. Code created from MS SQL Server Express Version 12.0.

    SELECT (YEAR(Date) * 100) + MONTH(Date) AS yyyyMM
    FROM [Order]
    ...
    GROUP BY (YEAR(Date) * 100) + MONTH(Date)
    ORDER BY yyyyMM
    
    0 讨论(0)
  • 2020-11-27 16:36

    For mariaDB you can:

    SELECT DATE_FORMAT(date, '%m-%Y')
    FROM [Order]
    GROUP BY 
    DATE_FORMAT(date, '%m-%Y')
    

    Link: https://mariadb.com/kb/en/library/date_format/

    0 讨论(0)
  • 2020-11-27 16:37

    SQL Server 2012 above, I prefer use format() function, more simplify.

    SELECT format(date,'MM.yyyy') AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada 
    FROM [Order]
    WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
    GROUP BY format(date,'MM.yyyy')
    
    0 讨论(0)
提交回复
热议问题