mysql – 按周/月间隔分组

前端之家收集整理的这篇文章主要介绍了mysql – 按周/月间隔分组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用MySQL,我有下表:

| clicks | int  |
|   period  | date |

我希望能够生成这样的报告,其中期间在过去4周内完成:

|   period    | clicks |
|  1/7 - 7/5  |  1000  | 
| 25/6 - 31/7 |  ....  |
| 18/6 - 24/6 |  ....  |
| 12/6 - 18/6 |  ....  |

或在过去3个月内:

| period | clicks |
|  July  |  ....  |
|  June  |  ....  |
| April  |  ....  |

任何想法如何制作可以生成等效日期范围和点击次数的选择查询

最佳答案
SELECT
 WEEKOFYEAR(`date`) AS period,SUM(clicks) AS clicks
FROM `tablename`
WHERE `date` >= CURDATE() - INTERVAL 4 WEEK
GROUP BY period

SELECT
 MONTH(`date`) AS period,SUM(clicks) AS clicks
FROM `tablename`
WHERE `date` >= CURDATE() - INTERVAL 3 MONTH
GROUP BY period

原文链接:https://www.f2er.com/mysql/433953.html

猜你在找的MySQL相关文章