sql >> Database >  >> RDS >> Sqlserver

SQL-groepering op maand en jaar

SELECT CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4)) 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 CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4))

Of zoals @40-Love al zei, je kunt casten met voorloopnullen:

GROUP BY 
  CAST(YEAR(date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(date) AS VARCHAR(2)), 2) 


  1. MyCLI – Een MySQL/MariaDB-client met automatische aanvulling en syntaxismarkering

  2. Best practices voor MySQL-replicatie

  3. Hoe "X Rows Selected" in SQLcl &SQL*Plus (Oracle) te verwijderen

  4. Tabel- of kolomnaam mag niet beginnen met numeriek?