MySQL中每行的最后n天汇总数据

时间:2016-06-29 08:10:12

标签: mysql sql

我有以下格式的数据 -

Date        Amount
1/1/2000       1
2/1/2000       1    
3/1/2000       1
4/1/2000       2
5/1/2000       1
6/1/2000       1
7/1/2000       1

此处,每行代表当天收集的金额,我想准备一张表,其中每行代表过去3天收集的金额。因此,对于3/1/2000 - 它将显示金额= 3(金额1在1/1,1在2/1和1在3/1,所以1 + 1 + 1 = 3

因此,从上面的数据来看,我想要的表是 -

Date        Amount
1/1/2000       1    //1
2/1/2000       2    //1+1    
3/1/2000       3    //1+1+1
4/1/2000       4    //1+1+2
5/1/2000       4    //1+2+1
6/1/2000       4    //2+1+1
7/1/2000       3    //1+1+1

如何为此编写SQL查询?

我试过了 -

select date, sum(amount) as amount_sum
from SQLTABLE
where DATEDIFF(date,date)<=2 
group by date

2 个答案:

答案 0 :(得分:1)

您可以使用相关子查询来获取前两个记录的Amount值:

SELECT `Date`, 
       Amount + 
       COALESCE((SELECT Amount 
                 FROM mytable AS t2
                 WHERE t2.`Date` < t1.`Date`
                 ORDER BY `Date` DESC LIMIT 1), 0) +
       COALESCE((SELECT Amount 
                 FROM mytable AS t2
                 WHERE t2.`Date` < t1.`Date`
                 ORDER BY `Date` DESC LIMIT 1, 1), 0) AS Amount
FROM mytable AS t1 

即使连续记录之间存在间隙,上述查询仍然有效。

修改

如果连续记录之间存在无间隙,则可以使用以下查询:

SELECT `Date`,       
       COALESCE((SELECT SUM(Amount)
                 FROM mytable AS t2
                 WHERE t2.date <= t1.date AND DATEDIFF(t1.date,t2.date) <= 2
                 ORDER BY `Date` DESC LIMIT 1), 0) AS Amount
FROM mytable AS t1 

答案 1 :(得分:1)

这可以通过使用子选择来完成。

SELECT date, 
       (SELECT sum(amount) 
       from SQLTABLE t2 
       WHERE DATEDIFF(t1.date,t2.date) IN (0,1,2)) amount_sum 
from SQLTABLE t1