一个简单的相关子查询就可以了。
create table test(transaction_date date,value int);
insert test values
('2024-01-01', 20),
('2024-01-02', 80),
('2024-01-03', 30),
('2024-02-01', 10),
('2024-02-02', 50),
('2024-03-03', 40),
('2024-03-05', 20),
('2024-04-02', 150),
('2024-04-03', 30),
('2024-05-04', 20),
('2024-05-05', 250),
('2024-06-03', 30),
('2024-06-04', 20),
('2024-07-02', 250),
('2024-07-10', 130)
;
select * from test;
--result set:
+------------------+-------+
| transaction_date | value |
+------------------+-------+
| 2024-01-01 | 20 |
| 2024-01-02 | 80 |
| 2024-01-03 | 30 |
| 2024-02-01 | 10 |
| 2024-02-02 | 50 |
| 2024-03-03 | 40 |
| 2024-03-05 | 20 |
| 2024-04-02 | 150 |
| 2024-04-03 | 30 |
| 2024-05-04 | 20 |
| 2024-05-05 | 250 |
| 2024-06-03 | 30 |
| 2024-06-04 | 20 |
| 2024-07-02 | 250 |
| 2024-07-10 | 130 |
+------------------+-------+
查询如下:
select transaction_date,
date_sub(transaction_date,interval +90 day) as date_diff,
(select sum(value) from test where transaction_date between date_sub(t.transaction_date,interval +90 day) and t.transaction_date ) as value
from test t;
-- result set:
+------------------+------------+-------+
| transaction_date | date_diff | value |
+------------------+------------+-------+
| 2024-01-01 | 2023-10-03 | 20 |
| 2024-01-02 | 2023-10-04 | 100 |
| 2024-01-03 | 2023-10-05 | 130 |
| 2024-02-01 | 2023-11-03 | 140 |
| 2024-02-02 | 2023-11-04 | 190 |
| 2024-03-03 | 2023-12-04 | 230 |
| 2024-03-05 | 2023-12-06 | 250 |
| 2024-04-02 | 2024-01-03 | 300 |
| 2024-04-03 | 2024-01-04 | 300 |
| 2024-05-04 | 2024-02-04 | 260 |
| 2024-05-05 | 2024-02-05 | 510 |
| 2024-06-03 | 2024-03-05 | 500 |
| 2024-06-04 | 2024-03-06 | 500 |
| 2024-07-02 | 2024-04-03 | 600 |
| 2024-07-10 | 2024-04-11 | 700 |
+------------------+------------+-------+