gpt4 book ai didi

mysql - 是否可以按 3 个月为周期对结果进行分组?

转载 作者:可可西里 更新时间:2023-11-01 07:49:44 24 4
gpt4 key购买 nike

我正在尝试按从当月开始的 3 个月期间对结果进行分组,如下所示:

row1      15 -- This should contain November, September and October
row2 25 -- This should contain August, July and June
row3 5 -- This should contain May, April and March
row4 2 -- This is should contain February and Janvier

我不知道如何做到这一点。有什么帮助吗?

到目前为止我可以按月分组:

SELECT MONTH(date), MONTHNAME(date) as month, COUNT(*) FROM table_name WHERE MONTH(date) < NOW()  GROUP BY MONTH(date) ORDER BY MONTH(date) DESC

谢谢

最佳答案

您可以使用 PERIOD_DIFF和一些数学来查找记录。

-- This line creates YYYYMM representation of today; you can use PHP instead
SET @T1 = DATE_FORMAT(CURRENT_DATE, '%Y%m');

SELECT MIN(`date`) AS `Range Start`, MAX(`date`) AS `Range End`, COUNT(*) AS `Count`
FROM `table`
GROUP BY FLOOR(PERIOD_DIFF(@T1, DATE_FORMAT(`date`, '%Y%m')) / 3)
ORDER BY 1 DESC

示例输出:

Range Start  Range End   Count
----------- ---------- -----
2013-09-01 2013-11-26 87
2013-06-01 2013-08-31 92
2013-03-01 2013-05-31 92
2012-12-01 2013-02-28 90
2012-09-01 2012-11-30 91

PERIOD_DIFF 返回期间 P1 和 P2 之间的月数(两个参数都是 YYYYMM 格式的字符串)。

在上面的查询中,我们计算每一行的月份差异(例如,NOV-2013 为 0,OCT-2013 为 1,SEP-2013 为 2,AUG-2013 为 3 等等)。

差值除以 3 加上 FLOOR 得出季度数(NOV-2013 为 0.00 -> 0,OCT-2013 为 0.33 -> 0,SEP-2013 为 0.66 -> 0,AUG -2013 是 1.00 -> 1,依此类推)。

关于mysql - 是否可以按 3 个月为周期对结果进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20212620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com