SQL按月份和年份分组

我不知道我应该在下面的SQL查询中写下如何显示“date”列:“month-year” – “9-2011”。

SELECT MONTH(date) + '.' + YEAR(date) 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 MONTH(date), YEAR(date) 

所以,我想要做的是从第一列更改数据显示月份和年份,而不是仅显示月份。

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

或者@ 40-Love提到你可以用前面的零来施放:

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

我猜是MS SQL,因为它看起来像MS SQL语法。

所以你应该像在select前面一样放置在组中:

 Select MONTH(date)+'-'+YEAR(date), .... ... ... ... group by MONTH(date)+'-'+YEAR(date) 

如果我理解正确。 为了根据请求对结果进行分组,您的Group By子句需要与您的select语句具有相同的expression式。

 GROUP BY MONTH(date) + '.' + YEAR(date) 

要将date显示为“月份 – date”格式,请更改“。”。 到“ – ”完整的语法将是这样的。

 SELECT MONTH(date) + '-' + YEAR(date) 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 MONTH(date) + '.' + YEAR(date) 

在postgresql中,我可以使用date格式函数(to_char)编写一个类似的查询,并按date分组:

 SELECT to_char (datum, 'MM-YYYY') AS mjesec FROM test GROUP BY datum ORDER BY datum; 

这样的东西肯定可以用SQL-Server来做,不是吗?

如果你想保持date时间数据types的字段,请尝试使用这个:

 SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada FROM [Order] o WHERE (idCustomer = 1) AND (o.[date] BETWEEN '2001-11-3' AND '2011-11-3') GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0) 

它也很容易改变成几小时,几天,几周,几年…
我希望这对某个人有用,

问候!