按月和年进行 SQL 分组
在 SQL 中,按月和年对数据进行分组是分析时态数据时的常见任务。为此,您可以使用 MONTH() 和 YEAR() 函数以及 GROUP BY 子句。
问题陈述
用户在查询时遇到问题订单表,将“日期”列显示为“月-年”(例如“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)
但是,此查询仅显示月份(例如“9”),并且用户希望在输出中包含月份和年份。
解决方案
要解决此问题,您可以使用 CAST() 函数来转换月份和将年份值转换为字符串并用连字符将它们连接起来。这是更新后的查询:
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))
此查询将以所需的格式返回“日期”列,显示月份和年份。
另一个选项是在转换为时使用前导零确保格式一致。这可以使用 right() 函数来实现:
GROUP BY CAST(YEAR(date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(date) AS VARCHAR(2)), 2)
此方法将为单位数月份值添加前导零,从而形成统一的格式(例如“09-2011”)。
以上是如何按月和年对 SQL 数据进行分组并将输出格式设置为'月-年”?的详细内容。更多信息请关注PHP中文网其他相关文章!