mysql 按周、一个月和最近三个月分组

mysql group by week , one month and three recent month

我有一个 table 列名为 started_at
我想按最后一天、一周、一个月和三个月获取新插入行的统计信息。
started_at 列格式默认为 MySQL 时间戳,即 string 。 在发布这个问题之前,我尝试了这个查询

SELECT WEEK(`started_at`) , COUNT(*) AS nbr FROM users_in_bots WHERE `bot_id` = 5529 GROUP BY WEEK (`started_at`);
SELECT MONTH(`started_at`), COUNT(*) AS nbr FROM users_in_bots WHERE `bot_id` = 5529 GROUP BY MONTH(`started_at`);


结果不是我想要的。 我想通过一次查询获得所有统计信息。

table 结构:

CREATE TABLE `users_in_bots` (
  `user_id` bigint(20) NOT NULL,
  `bot_id` bigint(20) NOT NULL,
  `started_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;



示例行:

INSERT INTO `users_in_bots` (`user_id`, `bot_id`, `started_at`) VALUES
(2314, 509492849, '2022-02-27 03:59:21'),
(28779, 210686266, '2022-03-03 21:51:38'),
(28779, 503513058, '2022-04-01 12:28:37'),
(28779, 515774720, '2022-03-25 08:25:16'),
(28779, 518099352, '2022-03-22 17:22:38'),
(28779, 519646468, '2022-03-04 22:02:02'),
(84588, 517141146, '2022-03-28 12:36:45'),
(87075, 509498849, '2022-02-27 03:59:21'),
(116264, 210509102, '2022-02-27 00:02:54'),
(116264, 212268136, '2022-02-27 00:29:06');



预期输出(我希望在我的应用程序中使用的内容):
过去 24 小时内的新用户:42
上周新用户:532
上月新增用户:4568
和第 3 个月和第 6 个月以及所有时间一样。

您可以使用条件聚合来获得您想要的结果。例如:

SELECT SUM(started_at BETWEEN NOW() - INTERVAL 1 HOUR AND NOW()) last_hour,
       SUM(started_at BETWEEN CURDATE() - INTERVAL 1 WEEK AND CURDATE()) last_week,
       SUM(started_at BETWEEN CURDATE() - INTERVAL 1 MONTH AND CURDATE()) last_month,
       SUM(started_at BETWEEN CURDATE() - INTERVAL 3 MONTH AND CURDATE()) last_3month,
       SUM(started_at BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE()) last_6month
FROM users_in_bots

输出(截至 2022-04-13 的示例数据):

last_hour   last_week   last_month  last_3month last_6month
0           0           4           10          10

Demo on dbfiddle