[英]MySQL GROUP BY query group results by week, month
I have a table named "counter" that has 3 fields:我有一个名为“counter”的表,它有 3 个字段:
| Field | Type | Null | Key | Default | Extra |
+--------+------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| record | datetime | YES | | NULL | |
| passed | tinyint(1) | YES | | NULL | |
+--------+------------+------+-----+---------+----------------+
My table records我的表记录
mysql> SELECT record, passed FROM counter;
+---------------------+--------+
| record | passed |
+---------------------+--------+
| 2019-09-19 00:00:00 | 1 |
I would like to make a query to group the results by weeks, and months from the field record.我想进行查询,以从现场记录中按周和月对结果进行分组。
I have tried to do it like this but doesn't look right我试过这样做,但看起来不正确
SELECT DATE_FORMAT(record, '%d-%m-%Y') AS ts, COUNT(*) FROM counter WHERE record >= '2019-10-09' AND record < '2019-10-09' + INTERVAL 7 DAY GROUP BY DATE_FORMAT(record, '%d-%m-%Y');
Simple grouping with date extraction must work使用日期提取进行简单分组必须有效
select
EXTRACT(YEAR FROM record) V_YEAR,
EXTRACT(MONTH FROM record) V_MONTH,
EXTRACT(WEEK FROM record) V_WEEK,
COUNT(*)
FROM COUNTER
GROUP BY
EXTRACT(YEAR FROM record) ,
EXTRACT(MONTH FROM record) ,
EXTRACT(WEEK FROM record)
edit same works with DATE_FORMAT(date, format)
as well使用DATE_FORMAT(date, format)
编辑相同的作品
select
DATE_FORMAT(record, '%Y') V_YEAR,
DATE_FORMAT(record, '%M') V_MONTH,
DATE_FORMAT(record, '%d') V_WEEK,
COUNT(*)
FROM COUNTER
GROUP BY
DATE_FORMAT(record, '%Y') ,
DATE_FORMAT(record, '%M') ,
DATE_FORMAT(record, '%d')
Number of passes, fails etc per week:每周通过、失败等次数:
SELECT week(record_date) as weekofyear, sum(passed) as numpasses, count(*) - sum(passed) as numfails, count(*) as total
FROM counter
WHERE record_date >= '2019-01-01' and record_date < '2020-01-01'
GROUP BY week(record_date)
Swap week for month etc换周换月等
MySQL supports ROLLUP which can summarise weeks and months in the same statement: MySQL 支持 ROLLUP,可以在同一语句中汇总周和月:
SELECT month(record_date) as monthofyear, week(record_date) as weekofyear, sum(passed) as numpasses, count(*) - sum(passed) as numfails, count(*) as total
FROM counter
WHERE record_date >= '2019-01-01' and record_date < '2020-01-01'
GROUP BY month(record_date), week(record_date) WITH ROLLUP
lines where the week is null are the total for the month周为 null 的行是该月的总数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.