1

下面是我的mysql表:

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)

我希望得到过去 12 个月的主键 cr_num 的按月计数。

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 月的记录。

我不是来自数据库背景,所以我没有深入研究我可以尝试的内容。

4

2 回答 2

1

您的条件 (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)
于 2020-10-28T12:23:45.440 回答
1

您可以使用函数LAST_DAY()按月分组并将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);
于 2020-10-28T12:28:21.640 回答