MySQL 中的奇怪分组行为

Weird behavior of grouping in MySQL

我在MySQL数据库中有一个这样的table:

CREATE TABLE metrics (
  id int(11) NOT NULL AUTO_INCREMENT,
  date date NOT NULL,
  value int(11) NOT NULL,
  PRIMARY KEY (id)
) ENGINE InnoDB AUTO_INCREMENT=1 CHARSET=utf8mb4;

具有以下值:

INSERT INTO metrics (date, value)
VALUES 
    ('2022-04-01', 1),
    ('2022-04-02', 1),
    ('2022-04-03', 1),
    ('2022-04-04', 1),
    ('2022-04-05', 1),
    ('2022-04-06', 1),
    ('2022-04-07', 1),
    ('2022-04-08', 1),
    ('2022-04-09', 1),
    ('2022-04-10', 1),
    ('2022-04-11', 1),
    ('2022-04-12', 1),
    ('2022-04-13', 1),
    ('2022-04-14', 1);

我想获得按周分组的值总和。 MySQL 中的默认周是从周一到周日,但我需要从周日到周六按周分组,所以这是我的查询:

SELECT
    (DATE_SUB(date, INTERVAL WEEKDAY(date) DAY) - INTERVAL 86400000000 MICROSECOND) AS week_start,
    SUM(value) AS value__sum
FROM
    metrics
GROUP BY
    (DATE_SUB(date, INTERVAL WEEKDAY(date) DAY) - INTERVAL 86400000000 MICROSECOND)
ORDER BY
    week_start ASC;

INTERVAL 86400000000 MICROSECOND 这个区间很奇怪,因为 Django ORM 是这样做的。无论如何,我得到了这样的结果:

week_start         |value__sum|
-------------------+----------+
2022-03-27 00:00:00|         3|
2022-04-03 00:00:00|         7|
2022-04-10 00:00:00|         4|

如您所见,week_start 值是正确的,它是星期日,但 value__sum 包含周一至周日错误时间段的数据。 也许我错过了什么?

这对你有用吗?

SELECT
    DATE_SUB(
      date, INTERVAL WEEKDAY(DATE_SUB(date, INTERVAL -1 DAY)) DAY
    ) AS week_start,    
    SUM(value) as value__sum
FROM
    metrics
GROUP BY
    week_start
ORDER BY
    week_start ASC;

我减去了WEEKDAY里面的天。

这导致:

week_start value__sum
2022-03-27 2
2022-04-03 7
2022-04-10 5

您可以简单地使用 week()。如果这不是在正确的日期拆分,您可以使用 week(date_add, interval 1 day)) 将 1 替换为您需要的数字(正数或负数)。

select
  week(date) "week",
  sum(value) "value"
from metrics
group by week(date)
order by week(date);
week | value
---: | ----:
  13 |     2
  14 |     7
  15 |     5

db<>fiddle here