从当前月份开始获取 mySQL 中按月计算的记录数

Get month-wise count of records in mySQL starting with the current month

下面是我的mysqltable:

mysql> DESCRIBE mytable;
+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| url_timestamp | timestamp    | NO   |     | NULL    |       |
| cr_num        | varchar(50)  | NO   |     | NULL    |       |
| status        | varchar(255) | NO   |     | NULL    |       |
| rollback_date | timestamp    | YES  |     | NULL    |       |
| rollback_user | varchar(255) | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

我希望获得 cr_num 的按月计数,这是过去 12 个月的主键。

mysql> SELECT MONTHNAME(url_timestamp) , COUNT(url_timestamp) FROM mytable WHERE status='PRODUCTION' and url_timestamp >= NOW() - INTERVAL 1 YEAR GROUP BY MONTHNAME(url_timestamp);
+--------------------------+----------------------+
| MONTHNAME(url_timestamp) | COUNT(url_timestamp) |
+--------------------------+----------------------+
| November                 |                   43 |
| December                 |                   69 |
| January                  |                  220 |
| October                  |                  225 |
| February                 |                  209 |
| March                    |                  123 |
| April                    |                   93 |
| May                      |                  113 |
| June                     |                  217 |
| July                     |                  129 |
| August                   |                  185 |
| September                |                  415 |
+--------------------------+----------------------+
12 rows in set (0.01 sec)

我得到的输出存在三个问题。

  1. 我希望输出从当前月份开始排序,即从 2020 年 10 月一直回到 2019 年 11 月。

  2. 11 月和 12 月来自上一年,即 2019 年;所以我想在每个月旁边显示年份。

  3. 我只想获取 2020 年的数据,因此不应显示 11 月和 12 月的记录。

我不是数据库背景的,所以我没有深入研究我本可以尝试的东西。

您的条件 (2) 和 (3) 不兼容。仅获取今年的月数:

SELECT MONTHNAME(url_timestamp), COUNT(*)
FROM mytable
WHERE status = 'PRODUCTION' AND
      YEAR(url_timestamp) = YEAR(NOW())
GROUP BY MONTHNAME(url_timestamp)
ORDER BY MIN(url_timestamp)

您可以使用函数 LAST_DAY() to group by month and DATE_FORMAT() 将月份格式化为年份:

SELECT DATE_FORMAT(LAST_DAY(url_timestamp), '%M %Y') month,
       COUNT(url_timestamp) counter
FROM mytable 
WHERE status='PRODUCTION' and url_timestamp >= NOW() - INTERVAL 1 YEAR 
GROUP BY month;

要使行正确排序,您还需要 GROUP BY LAST_DAY(url_timestamp) 以便可以在 ORDER BY 子句中使用它:

SELECT DATE_FORMAT(LAST_DAY(url_timestamp), '%M %Y') month,
       COUNT(url_timestamp) counter
FROM mytable 
WHERE status='PRODUCTION' and url_timestamp >= NOW() - INTERVAL 1 YEAR 
GROUP BY month, LAST_DAY(url_timestamp)
ORDER BY LAST_DAY(url_timestamp);