gpt4 book ai didi

mysql - 在 mysql 中创建一段时间内的滚动总和

转载 作者:行者123 更新时间:2023-11-29 01:21:53 25 4
gpt4 key购买 nike

我有一个包含列 datetime_spent 的表格。我想为每个日期 D 找到一段时间内“time_spent”值的总和:(D-7 - D),即。过去一周 + 今天。

我想不出办法来做到这一点,因为我只能找到总和的例子,而不是可变时间段内的总和。

这是一个数据集示例:

CREATE TABLE rolling_total
(
date date,
time_spent int
);

INSERT INTO rolling_total VALUES ('2013-09-01','2'),
('2013-09-02','1'),
('2013-09-03','3'),
('2013-09-04','4'),
('2013-09-05','2'),
('2013-09-06','5'),
('2013-09-07','3'),
('2013-09-08','2'),
('2013-09-09','1'),
('2013-09-10','1'),
('2013-09-11','1'),
('2013-09-12','3'),
('2013-09-13','2'),
('2013-09-14','4'),
('2013-09-15','6'),
('2013-09-16','1'),
('2013-09-17','2'),
('2013-09-18','3'),
('2013-09-19','4'),
('2013-09-20','1'),
('2013-09-21','6'),
('2013-09-22','5'),
('2013-09-23','3'),
('2013-09-24','1'),
('2013-09-25','5'),
('2013-09-26','2'),
('2013-09-27','1'),
('2013-09-28','4'),
('2013-09-29','3'),
('2013-09-30','2')

结果如下:

date       | time_spent   | rolling_week_total
2013-09-01 | 2 | 2
2013-09-02 | 1 | 3
2013-09-03 | 3 | 6
2013-09-04 | 4 | 10
2013-09-05 | 2 | 12
2013-09-06 | 5 | 17
2013-09-07 | 3 | 20
2013-09-08 | 2 | 22
// now we omit values that are older than seven days
2013-09-09 | 1 | 21
2013-09-10 | 1 | 21
...

最佳答案

还有一个解决方案

SELECT r1.date, r1.time_spent, sum(r2.time_spent) AS rolling_week_total
FROM rolling_total AS r1 JOIN rolling_total AS r2
ON datediff(r1.date, r2.date) BETWEEN 0 AND 7
GROUP BY r1.date
ORDER BY r1.date
LIMIT 8

关于mysql - 在 mysql 中创建一段时间内的滚动总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19213633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com