使用 SQL 数据库时,通常需要按时间段(例如月或年)对数据进行分组。默认情况下,SQL 的 GROUP BY 子句根据各个月份或年份对行进行分组。但是,您可能会遇到需要以更易于理解的格式显示结果的情况,例如“月-年”。
假设您有一个按月和年对数据进行分组的查询,并按如下方式显示结果:
SELECT MONTH(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”。目标是修改查询以组合格式显示月份和年份,例如“9-2011”。
SELECT CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4)) AS Mjesec, ...
GROUP BY CAST(YEAR(date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(date) AS VARCHAR(2)), 2)
以上是如何以人类可读的格式按月和年对 SQL 结果进行分组?的详细内容。更多信息请关注PHP中文网其他相关文章!